问题
I am trying to make draw a circle based on the battery percentage. I have the following code:
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);
I am trying to get similar to Battery Widget Reborn, where its a circle path drawn based on a percentage, could someone please help.
Edit:
below is a shot of what i am trying to accomplish
回答1:
You should be able to do this with Path.addArc()
. You just have to define the bounds of the enclosing rectangle, the start angle, and how many degrees to sweep.
Something like:
RectF box = new RectF(0,0,bmp.getWidth(),bmp.getHeight());
float sweep = 360 * level * 0.01f;
circle.addArc(box, 0, sweep);
回答2:
You can use this class as a full working example. You can also add the text in the view, but that goes beyond the question...
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);
}
}
来源:https://stackoverflow.com/questions/14988701/battery-circle-like-battery-widget-reborn