用不同的边框颜色Android绘制圆圈

时间:2014-03-06 11:41:13

标签: android

public static Bitmap drawCircle(int width,int height, int borderWidth) {
    Bitmap canvasBitmap = Bitmap.createBitmap( width, height, Bitmap.Config.ARGB_8888);
    BitmapShader shader = new BitmapShader(canvasBitmap, TileMode.CLAMP,      
            TileMode.CLAMP);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setShader(shader);
    paint.setShader(null);
    paint.setStyle(Paint.Style.STROKE);
    paint.setColor(Color.WHITE);
    paint.setStrokeWidth(borderWidth);  
    Canvas canvas = new Canvas(canvasBitmap);
    float radius = width > height ? ((float) height) / 2f : ((float) width) / 2f;
    canvas.drawCircle(width / 2, height / 2, radius - borderWidth / 2, paint);
    return canvasBitmap;
}

简单的代码绘制一个带有白色边框的圆圈,但是我希望边框的一部分是黑色而另一部分是白色的。 40%的黑色,60%的白色

如何做到这一点?

3 个答案:

答案 0 :(得分:8)

试试此代码

class MyView extends View
{
    private Paint paint;

    public MyView(Context context, int x, int y)
    {
        super(context);
        paint = new Paint();
        // PorterDuffXfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.CLEAR);

        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.RED);


        paint.setAlpha(255);
        // paint.setXfermode(xfermode);
        paint.setAntiAlias(true);
        // setBackgroundColor(Color.BLACK);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        canvas.drawCircle(100, 100, 50, paint);
    }
}

答案 1 :(得分:3)

这是一种用一种颜色填充圆圈并用另一种颜色抚摸圆形边框的实用方法。

使用第二种方法传入现有的Paint实例,例如在onDraw()期间设置反别名标志或防止内存分配。

public static void fillCircleStrokeBorder(
        Canvas c, float cx, float cy, float radius,
        int circleColor, float borderWidth, int borderColor) {
    fillCircleStrokeBorder(c, cx, cy, radius, circleColor, borderWidth, borderColor, new Paint());
}

public static void fillCircleStrokeBorder(
        Canvas c, float cx, float cy, float radius,
        int circleColor, float borderWidth, int borderColor, Paint p) {

    int saveColor = p.getColor();
    p.setColor(circleColor);
    Paint.Style saveStyle = p.getStyle();
    p.setStyle(Paint.Style.FILL);
    c.drawCircle(cx, cy, radius, p);
    if (borderWidth > 0) {
        p.setColor(borderColor);
        p.setStyle(Paint.Style.STROKE);
        float saveStrokeWidth = p.getStrokeWidth();
        p.setStrokeWidth(borderWidth);
        c.drawCircle(cx, cy, radius - (borderWidth / 2), p);
        p.setStrokeWidth(saveStrokeWidth);
    }
    p.setColor(saveColor);
    p.setStyle(saveStyle);
}

答案 2 :(得分:0)

只需用一种颜色绘制全尺寸的圆圈,然后在相同的坐标处再次绘制圆圈,但是使用不同的颜色和较小的半径,然后缩小半径,无论您需要多少,这将是最琐碎的方式。