用不同的边框颜色绘制圆圈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%是白色的

如何才能做到这一点?

Solutions Collecting From Web of "用不同的边框颜色绘制圆圈Android"

试试这个代码

 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); } } 

这里有一个实用的方法,用一种颜色填充一个圆圈,用另一种颜色来画圆圈。

使用第二种方法传入现有的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); } 

用一种颜色画一个完整尺寸的圆,然后在相同的坐标上再画圆,但是颜色不同,半径较小,然后按照你需要的尺寸缩小半径,这将是最微不足道的方法去做吧。