Android 用 2 种颜色绘制圆圈(饼图)

问题描述:

这是我在 *.com 上的第一个问题,如果我做错了,请原谅自己.

This is my first question here at *.com so excuse myself if i'm doing stuff wrong.

我想创建一个基本上类似于进度条的圆圈.现在我想通过一些代码设置百分比.

I want to create a circle which basically is like a progress bar. Now I'd like to set the percentage through some code.

我想要实现的是:https://raw.github.com/psud/Melde-App/master/res/drawable-hdpi/circlemiddle.png

我的问题:

  1. 无法使用两种颜色的圆圈(已经在论坛上搜索了几个小时并找到了与我类似的问题的解决方案,但我无法将这些解决方案实施到我的应用程序中.我已经阅读了很多关于 canvas.drawArc(...) 但似乎不知道如何使用它.
  2. 如何将画布放入布局中?(我有一个 xml 布局,应该在特定布局内绘制画布,而不更改布局的其余部分).

谢谢.

这只是一个提示.它只是一个在同一个矩形中绘制两条弧的视图:第一条弧跨度从角度 0 到 360.第二个(在第一个上方)跨度从 0 到取决于百分比的角度.

This is only a hint. It is simply a view that draw two arcs in the same rect: First arc spans from angle 0 to 360. The second one (above the first) spans from 0 to an angle that depends on the percentage.

public class PercentView extends View {

    public PercentView (Context context) {
        super(context);
        init();
    }
    public PercentView (Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    public PercentView (Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }
    private void init() {
        paint = new Paint();
        paint.setColor(getContext().getResources().getColor(R.color.lightblue));
        paint.setAntiAlias(true);
        paint.setStyle(Paint.Style.FILL);
        bgpaint = new Paint();
        bgpaint.setColor(getContext().getResources().getColor(R.color.darkblue));
        bgpaint.setAntiAlias(true);
        bgpaint.setStyle(Paint.Style.FILL);
        rect = new RectF();
    }
    Paint paint;
    Paint bgpaint;
    RectF rect;
    float percentage = 0;
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //draw background circle anyway
        int left = 0;
        int width = getWidth();
        int top = 0;
        rect.set(left, top, left+width, top + width); 
        canvas.drawArc(rect, -90, 360, true, bgpaint);
        if(percentage!=0) {
            canvas.drawArc(rect, -90, (360*percentage), true, paint);
        }
    }
    public void setPercentage(float percentage) {
        this.percentage = percentage / 100;
        invalidate();
    }
}

添加到您的布局:

<bla.bla.PercentView
            android:id="@+id/percentview"
            android:layout_width="100dp"
            android:layout_height="100dp" />