[android]圆圈用SweepGradient来制作动画

时间:2013-10-17 13:45:45

标签: android android-canvas

enter image description here

嗨,我想画一个如图所示的圆圈。我的值范围是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设置为任意定义的值。

0 个答案:

没有答案