2

I am writing a custom view in android. I want to draw a circle that cover all width and height of my view. this is my code

private void init() {

    bgpaint = new Paint();
    bgpaint.setColor(bgColor);
    bgpaint.setAntiAlias(true);
    bgpaint.setStyle(Paint.Style.STROKE);
    bgpaint.setStrokeWidth(strokeWidth);
    rect = new RectF();

}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // draw background circle anyway
           int strokeWidth = 50;
    rect.set(strokeWidth, strokeWidth, getwidth()- strokeWidth, 
            getheight() - strokeWidth);
    canvas.drawArc(rect, -90, 360, fill, bgpaint);

}

But when I run result will be like this

enter image description here

I want be like this

enter image description here

What the problem with my code?

Cœur
  • 37,241
  • 25
  • 195
  • 267
aTa
  • 641
  • 2
  • 8
  • 20

1 Answers1

1

Probem is in setting your rectangle's coordinates. You must set half of stroke width, not whole stroke width.

    float left=strokeWidth / 2;
    float top=strokeWidth / 2;
    float right=minDimen - strokeWidth/ 2;
    float bottom=minDimen - strokeWidth / 2;
    rect.set(left, top, right,bottom);

Because it comes to circle, I assume your width and height of your circleView are the same dimension. That is minDimen in my code. Because I use smaller dimension of those two.

final int minDimen = Math.min(width, height);
setMeasuredDimension(minDimen, minDimen);  

(this must be called in onMeasure method) Anyway, it's good method to set width and height in same dimensions.

androidEnthusiast
  • 1,140
  • 1
  • 12
  • 21