像Battery Widget Reborn一样的电池圈

时间:2013-02-20 19:52:01

标签: android canvas battery

我试图根据电池百分比绘制一个圆圈。我有以下代码:

Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(200, 200, conf);

Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(Color.BLUE);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(5);

circle = new Path();
circle.addCircle(100, 100, level, Direction.CW);

Canvas canvas = new Canvas(bmp);
canvas.drawPath(circle, mPaint);

我想尝试类似于电池小工具重生,其中根据百分比绘制的圆形路径,有人可以帮助。

编辑:

下面是我想要完成的一个镜头

image of the percentage circle

2 个答案:

答案 0 :(得分:4)

您可以将此类用作完整的工作示例。您也可以在视图中添加文本,但这超出了问题...

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;

public class DrawView extends View {

    Paint mPaint = new Paint();

    public DrawView(Context context) {
        super(context);            
    }

    @Override
    public void onDraw(Canvas canvas) {

        Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG |
                Paint.DITHER_FLAG |
                Paint.ANTI_ALIAS_FLAG);
        mPaint.setDither(true);
        mPaint.setColor(Color.GRAY);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(1);

        int size = 200;
        int radius = 190;
        int delta = size - radius;
        int arcSize = (size - (delta / 2)) * 2;
        int percent = 42;

        //Thin circle
        canvas.drawCircle(size, size, radius, mPaint);

        //Arc
        mPaint.setColor(Color.parseColor("#33b5e5"));
        mPaint.setStrokeWidth(15);
        RectF box = new RectF(delta,delta,arcSize,arcSize);
        float sweep = 360 * percent * 0.01f;
        canvas.drawArc(box, 0, sweep, false, mPaint);

    }

}

答案 1 :(得分:2)

您应该可以使用Path.addArc()执行此操作。您只需定义包围矩形的边界,起始角度以及扫描的度数。

类似的东西:

RectF box = new RectF(0,0,bmp.getWidth(),bmp.getHeight());
float sweep = 360 * level * 0.01f;
circle.addArc(box, 0, sweep);