在 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);
这样,你就可以动态地改变圆弧的颜色、起始角度和扫过角度了。