3

我正在寻找的是一种以顺时针圆形方式显示图像的视图。当进度为 25% 时,应显示前 90 度,当进度为 100% 时,应绘制完整的 360 度。

它与使用 canvas.drawArc() 非常接近,但此方法仅适用于 Paint 对象,不适用于位图。

其他答案也仅适用于全彩: How To Make Circle Custom Progress Bar in Android

我发现这是一个非常困难的问题,我希望有人有解决方案。

4

1 回答 1

8

特此:

public class MyView extends View {

    private Bitmap mBitmap;
    private Paint mPaint;
    private RectF mOval;
    private float mAngle = 135;
    private Paint mTextPaint;

    public MyView(Context context) {
        super(context);
        // use your bitmap insted of R.drawable.ic_launcher
        mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mOval = new RectF();
        mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextPaint.setTextSize(48);
        mTextPaint.setTextAlign(Align.CENTER);
        mTextPaint.setColor(0xffffaa00);
        mTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        Matrix m = new Matrix();
        RectF src = new RectF(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
        RectF dst = new RectF(0, 0, w, h);
        m.setRectToRect(src, dst, ScaleToFit.CENTER);
        Shader shader = new BitmapShader(mBitmap, TileMode.CLAMP, TileMode.CLAMP);
        shader.setLocalMatrix(m);
        mPaint.setShader(shader);
        m.mapRect(mOval, src);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(0xff0000aa);
        canvas.drawArc(mOval, -90, mAngle, true, mPaint);
        canvas.drawText("click me", getWidth() / 2, getHeight() / 2, mTextPaint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float w2 = getWidth() / 2f;
        float h2 = getHeight() / 2f;
        mAngle = (float) Math.toDegrees(Math.atan2(event.getY() - h2, event.getX() - w2));
        mAngle += 90 + 360;
        mAngle %= 360;
        invalidate();
        return true;
    }
}
于 2013-11-01T12:18:35.170 回答