4

在此处输入图像描述

嗨,我正在尝试画一个如图所示的圆圈。我的值范围为 0-100。0-40 绿色 41-60 黄色 61-80 橙色和 81-100 红色。

视图应该从 0 缓慢地动画到定义的值,这是要实现的。

我尝试了以下代码,并尝试实现,代码如下:

public class GradiantActivity extends Activity {

/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(new GradientTestView(this));
}

private class GradientTestView extends View {
    private Paint mPaint;
    private final int[] mColors;
    private int CENTER_X;
    private int CENTER_Y;

    private Shader shader;
    /**
     * Radius coordinates to draw circle.
     */
    float r;

    public GradientTestView(Context context) {
        super(context);

        mColors = new int[] {
                0xFF00FF00, //Green
                0xFFFFFF00, //Yellow
                            //Orange
                0xFFFF0000 //Red
        };

        shader = new SweepGradient(0, 0, mColors, null);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(100);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.translate(CENTER_X, CENTER_Y);
        mPaint.setShader(shader);
        canvas.drawOval(new RectF(-r, -r, r, r), mPaint);

        //for different positioning
        //canvas.translate(0, CENTER_Y);
        //canvas.translate(-CENTER_X * 3 / 4, -CENTER_Y / 2);
        //canvas.translate(CENTER_X * 3 / 2, 0);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        CENTER_X = this.getWidth() / 2;
        CENTER_Y = this.getHeight() / 2;
        r = CENTER_Y / 2 - mPaint.getStrokeWidth() * 0.5f;
    }
}
}

请帮助将此视图从 0 设置为任何定义的值。

4

0 回答 0