效果圖
在 Android 中,如果你想要繪制一個圓角矩形并使其居中顯示,你可以使用 Canvas 類 drawRoundRect
方法。要使圓角矩形居中,你需要計算矩形的位置,這通常涉及到確定矩形左上角的位置(x, y),這樣矩形就可以在其容器中水平和垂直居中。以下是一個基本的步驟指南:
確定容器的尺寸:首先,你需要知道繪制圓角矩形的容器的寬度和高度。這通常是視圖的寬度和高度。
計算圓角矩形的尺寸:確定你想要繪制的圓角矩形的寬度和高度。
計算圓角矩形的位置:為了居中矩形,你需要計算其左上角的 x 和 y坐標。這可以通過從容器寬度和高度中減去矩形寬度和高度,然后除以 2 來實現。例如,x = (containerWidth - rectWidth) / 2 和 y = (containerHeight - rectHeight) / 2。
繪制圓角矩形:使用 Canvas 的 drawRoundRect 方法,傳遞計算出的 x、y 坐標,矩形的寬度和高度,以及圓角的半徑。
View源碼
package com.android.circlescalebar.view;import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;public class SignalGridView extends View {private Paint mPaint = new Paint();private int mStrength;public SignalGridView(Context context) {super(context);}public SignalGridView(Context context, @Nullable AttributeSet attrs) {super(context, attrs);}public SignalGridView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);mPaint.setColor(Color.GRAY); // 設置文字顏色mPaint.setTextSize(40); // 設置文字大小mPaint.setAntiAlias(true); // 設置抗鋸齒String text = "信號"; // 要繪制的文字float x = 20; // 文字開始的 x 坐標float y = 55; // 文字開始的 y 坐標canvas.drawText(text, x, y, mPaint); // 在指定位置繪制文// 繪制 5 個帶弧度的矩形float left = 110;float top = 22;float right = 120;float bottom = 60;float radius = 5; // 圓角半徑for (int i = 0; i < 5; i++) {RectF rect = new RectF(left, top, right, bottom);mPaint.setColor(mStrength <= i ? Color.GRAY : Color.GREEN); // 設置畫筆顏色canvas.drawRoundRect(rect, radius, radius, mPaint);left += 23; // 調整下一個矩形的位置right += 23;}}public void updateSignalStrength(int strength) {// Invalidate the view to trigger a redrawmStrength = strength;invalidate();}
}
調用實現
private Handler handler = new Handler(); private Runnable runnable; private SignalGridView signalGridView;@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //..signalGridView = findViewById(R.id.signalGridView);runnable = new Runnable() { private Random random = new Random(); @Override public void run() { int randomNumber = random.nextInt(5); // 生成0到4之間的隨機數 signalGridView.updateSignalStrength(randomNumber);handler.postDelayed(this, 200); // 每200毫秒執行一次 } }; handler.post(runnable); // 開始執行 }@Override protected void onDestroy() { super.onDestroy(); handler.removeCallbacks(runnable); // 停止執行 }
布局
<com.android.circlescalebar.view.SignalGridViewandroid:id="@+id/signalGridView"android:layout_width="85dp"android:layout_height="35dp"/>