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%的白色
如何才能做到这一点?
试试这个代码
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); }
只需用一种颜色绘制全尺寸的圆圈,然后在相同的坐标处再次绘制圆圈,但是使用不同的颜色和较小的半径,并缩小半径,无论你需要多少,这将是最简单的方法去做吧。