5

我正在尝试绘制一个圆圈的动画。在我的自定义视图中,我有

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(). 但是,屏幕上没有绘制任何内容。我尝试了几种变体,但无济于事。有什么我做错了吗?有没有更简单的方法来做到这一点?给定一个圆圈的百分比,我希望能够使圆圈的大部分成为屏幕上绘制的内容。

4

1 回答 1

9

这里有两件事:

  1. canvas.drawOval(...)在将弧线绘制到椭圆上之前,您必须先打电话。否则不会出现。这就是为什么我的方法不起作用的原因。

  2. 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.
}
于 2013-03-21T23:15:23.953 回答