Android draw a circle using Path

I'm trying to animate drawing a circle. In my user view, I have

private final Paint mPaint = new Paint() {
    {
        setDither(true);
        setStyle(Paint.Style.STROKE);
        setStrokeCap(Paint.Cap.ROUND);
        setStrokeJoin(Paint.Join.ROUND);
        setColor(Color.BLUE);
        setStrokeWidth(30.0f);
        setAntiAlias(true);
    }
};
...
protected void onDraw(Canvas canvas) {
    super.onDraw();
    if (mOval == null) {
        mOval = new RectF(getLeft(), getTop(), getRight(), getBottom());
    }
    if (mPath == null) {
        mPath = new Path();
    mPath.moveTo(0, getHeight() / 2);
    }

    float sweepAngle = Math.min((float) mElapsedTime / 1000 * 60 * 1, 1) * 360;
    if (sweepAngle == 0) {
        mPath.reset();
    } else if (mCurrentAngle != sweepAngle) {
    mPath.arcTo(mOval, mCurrentAngle, sweepAngle);
    }
    mCurrentAngle = sweepAngle;
    canvas.drawPath(mPath, mPaint);
}

At intervals, I update mElapsedTimeand call invalidate(). However, nothing is drawn on the screen. I tried several options, but to no avail. Is there something I'm doing wrong? Is there an easier way to do this? Given the percentage of the circle, I want most of the circle to be drawn on the screen.

+5
source share
1 answer

There are two things here:

: View:

private final Paint mArcPaint = new Paint() {
    {
        setDither(true);
        setStyle(Paint.Style.STROKE);
        setStrokeCap(Paint.Cap.ROUND);
        setStrokeJoin(Paint.Join.ROUND);
        setColor(Color.BLUE);
        setStrokeWidth(40.0f);
        setAntiAlias(true);
    }
};

private final Paint mOvalPaint = new Paint() {
    {
        setStyle(Paint.Style.FILL);
        setColor(Color.TRANSPARENT);
    }
};

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    RectF mOval = new RectF(left, top, right, bottom); //This is the area you want to draw on
    float sweepAngle = 270; //Calculate how much of an angle you want to sweep out here
    canvas.drawOval(mOval, mOvalPaint); 
    canvas.drawArc(mOval, 269, sweepAngle, false, mArcPaint); //270 is vertical. I found that starting the arc from just slightly less than vertical makes it look better when the circle is almost complete.
}
+8

All Articles