在 Android 中,要動態繪制圓弧(Arc),你可以使用 Canvas
類的 drawArc()
方法。以下是一個簡單的示例,展示了如何在自定義的 View 上動態繪制圓弧:
onDraw()
方法中使用 Canvas
的 drawArc()
方法繪制圓弧: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;
public class ArcView extends View {
private Paint paint;
private RectF arcRect;
private float startAngle;
private float sweepAngle;
private int color;
public ArcView(Context context) {
super(context);
init();
}
public ArcView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ArcView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
paint.setColor(Color.BLUE);
paint.setAntiAlias(true);
arcRect = new RectF();
startAngle = 0;
sweepAngle = 180;
color = Color.BLUE;
}
public void setArcColor(int color) {
this.color = color;
invalidate();
}
public void setArcStartAngle(float startAngle) {
this.startAngle = startAngle;
invalidate();
}
public void setArcSweepAngle(float sweepAngle) {
this.sweepAngle = sweepAngle;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 設置畫筆屬性
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(10);
// 設置圓弧矩形區域
arcRect.set(50, 50, 250, 250);
// 繪制圓弧
canvas.drawArc(arcRect, startAngle, sweepAngle, color);
}
}
<com.example.yourpackage.ArcView
android:id="@+id/arc_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
ArcView arcView = findViewById(R.id.arc_view);
arcView.setArcColor(Color.RED);
arcView.setArcStartAngle(0);
arcView.setArcSweepAngle(360);
這樣,你就可以動態地改變圓弧的顏色、起始角度和掃過角度了。