【问题标题】:Android draw circle with PathAndroid 用 Path 画圆
【发布时间】:2013-03-21 21:37:08
【问题描述】:

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

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

【问题讨论】:

    标签: android android-animation bezier


    【解决方案1】:

    这里有两件事:

    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.
    }
    

    【讨论】:

    • 如何在画布的中心绘制这个?
    • @user2095470,Canvas 支持getHeight()getWidth(),因此您应该能够根据此计算出mOval 的放置位置。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多