我正在尝试绘制一个圆圈的动画。在我的自定义 View 中,我有
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);
}
每隔一段时间,我会更新 mElapsedTime
并调用 invalidate()
。但是,屏幕上没有绘制任何内容。我尝试了几种变体,但无济于事。我做错了什么吗?有没有更简单的方法来做到这一点?给定一个圆的百分比,我希望能够使圆的大部分成为屏幕上绘制的内容。
最佳答案
这里有两件事:
在将圆弧绘制到椭圆上之前,您必须调用
canvas.drawOval(...)
。否则不会出现。这就是我的方法不起作用的原因。Canvas
有一个drawArc
方法,该方法采用起始角度和扫出度数。参见Canvas.drawArc(RectF, float, float, boolean, Paint)
.这就是我要画圆圈的原因。
编辑:这是来 self 的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.
}
关于Android用Path画圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15558673/