温馨提示×

android drawcircle能自定义边框吗

小樊
84
2024-12-08 17:18:23
栏目: 编程语言

在Android中,drawCircle()方法本身不支持直接自定义边框。但是,您可以通过以下步骤实现带有自定义边框的圆形:

  1. 创建一个自定义的Drawable类,继承自ShapeDrawableGradientDrawable。在这个类中,您可以设置圆形的属性,如颜色、大小和边框宽度及颜色。
public class CustomCircleDrawable extends ShapeDrawable {
    private int borderWidth;
    private int borderColor;

    public CustomCircleDrawable(int radius, int borderWidth, int borderColor) {
        super(new RectF(-radius, -radius, radius, radius));
        this.borderWidth = borderWidth;
        this.borderColor = borderColor;
    }

    @Override
    protected void onDraw(Canvas canvas, Rect bounds) {
        Paint paint = getPaint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(borderWidth);
        paint.setColor(borderColor);

        super.onDraw(canvas, bounds);
    }
}
  1. 在您的Activity或Fragment中,使用这个自定义Drawable类绘制圆形。
CustomCircleDrawable customCircleDrawable = new CustomCircleDrawable(radius, borderWidth, borderColor);
Canvas canvas = new Canvas();
canvas.drawCircle(width / 2f, height / 2f, radius, customCircleDrawable);

这样,您就可以创建一个带有自定义边框的圆形了。

0