我正在尝试制作一个圆圈的动画。在我的自定义视图中,我有
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()
。但是,屏幕上没有任何内容。我尝试了几种变化,但无济于事。有什么我做错了吗?有更简单的方法吗?给定一个圆圈的百分比,我希望能够在屏幕上绘制大部分圆圈。
答案 0 :(得分:9)
这里有两件事:
在将弧线绘制到椭圆上之前,您必须先调用canvas.drawOval(...)
。否则它不会出现。这就是我的方法不起作用的原因。
Canvas
有一个drawArc
方法,它采用起始角度和扫描度数。见Canvas.drawArc(RectF, float, float, boolean, Paint)
。这就是我想要画圈子的。
编辑:这是我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.
}