2014-03-06 79 views
7
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%爲白色繪製不同邊框顏色的圓Android

這怎麼辦?

+3

你正在路上。而不是畫圓,畫兩個弧。一個白色,另一個黑色。請參閱'canvas.drawArc(...)'。做一些簡單的數學運算... –

+0

我是probabl; y有drawarc params的問題,例如這不會給我畫任何東西RectF rect = new RectF(10,10,10,10); \t \t canvas.drawArc(rect,0,180,true,paint); – user3278732

回答

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

只需繪製你的圈子,在全尺寸用一種顏色,然後在同一座標重新繪製圓,但用不同的顏色,並以較小的半徑,縮小半徑但多少你需要,那將是最簡單的方法。