在我的Android应用程序中,我得到了一些小部件,我希望它们看起来像这些进度条。
现在我知道我不能使用任何外部库来执行此操作,因为小部件不支持大多数自定义视图。我见过大多数开发人员使用位图来绘制这样的东西。我可以画出一个完整的圆圈。但是如何使用位图绘制这个弧形进度条还是有其他方法吗?
感谢您的帮助。谢谢!
答案 0 :(得分:4)
回答我自己的问题:
如果有人在寻找这种小部件,我设法让它在代码之后工作。希望这会对某人有所帮助。
private Bitmap getWidgetBitmap(Context context, int percentage) {
int width = 400;
int height = 400;
int stroke = 30;
int padding = 5;
float density = context.getResources().getDisplayMetrics().density;
//Paint for arc stroke.
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG | Paint.ANTI_ALIAS_FLAG);
paint.setStrokeWidth(stroke);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeCap(Paint.Cap.ROUND);
//paint.setStrokeJoin(Paint.Join.ROUND);
//paint.setPathEffect(new CornerPathEffect(10) );
//Paint for text values.
Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setTextSize((int) (context.getResources().getDimension(R.dimen.widget_text_large_value) / density));
mTextPaint.setColor(Color.WHITE);
mTextPaint.setTextAlign(Paint.Align.CENTER);
final RectF arc = new RectF();
arc.set((stroke/2) + padding, (stroke/2) + padding, width-padding-(stroke/2), height-padding-(stroke/2));
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
//First draw full arc as background.
paint.setColor(Color.argb(75, 255, 255, 255));
canvas.drawArc(arc, 135, 275, false, paint);
//Then draw arc progress with actual value.
paint.setColor(Color.WHITE);
canvas.drawArc(arc, 135, 200, false, paint);
//Draw text value.
canvas.drawText(percentage + "%", bitmap.getWidth() / 2, (bitmap.getHeight() - mTextPaint.ascent()) / 2, mTextPaint);
//Draw widget title.
mTextPaint.setTextSize((int) (context.getResources().getDimension(R.dimen.widget_text_large_title) / density));
canvas.drawText(context.getString(R.string.widget_text_arc_battery), bitmap.getWidth() / 2, bitmap.getHeight()-(stroke+padding), mTextPaint);
return bitmap;
}
这产生了以下内容。
谢谢!
答案 1 :(得分:2)
是的,你需要一个位图,但它很容易在位图上绘制弧线,就像在自定义视图上绘制弧一样:
Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawArc(arcRect, startAngle, sweepAngle, false, paint);
RemoteViews views = new RemoteViews(updateService.getPackageName(), R.layout.widget);
views.setImageViewBitmap(R.id.image_view, bitmap);