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

时间:2013-11-01 16:43:29

标签: java android android-custom-view

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

我想创建一个基本上就像进度条的圆圈。现在我想通过一些代码来设置百分比。

我想要达到的目标是:https://raw.github.com/psud/Melde-App/master/res/drawable-hdpi/circlemiddle.png

我的问题:

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

2 个答案:

答案 0 :(得分:19)

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

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" />

答案 1 :(得分:2)

您可以使用此库(achartengine - https://code.google.com/p/achartengine/)轻松实现饼图,而不是滚动自己的解决方案。