int x = 10;
int y = 10;
int r = 4;
Paint mPaint = new Paint();
mPaint.setColor(0xFF0000);
Canvas mCanvas = new Canvas();
mCanvas.drawCircle(x,y,r,mPaint);
有没有办法将mCanvas
转换为Drawable?我的目标是生成具有特定形状和颜色的drawable。
由于
答案 0 :(得分:7)
对于像圈子一样的简单形状,我认为Shape Drawable会更容易。对于更复杂的事情,只需为Canvas创建一个Bitmap,然后创建Canvas并绘制到其中,然后从Bitmap创建一个Drawable。类似的东西:
int x = 10;
int y = 10;
int r = 4;
Paint mPaint = new Paint();
mPaint.setColor(0xFF0000);
Bitmap bitmap = Bitmap.createBitmap(/* read the docs*/);
Canvas mCanvas = new Canvas(bitmap);
mCanvas.drawCircle(x,y,r,mPaint);
BitmapDrawable drawable = new BitmapDrawable(getResources(), bitmap);
或许有点迂腐(希望增加你的理解),Canvas只是托管“绘制”调用并绘制到你指定的位图。这意味着:
setBitmap()
。答案 1 :(得分:0)
从另一篇文章中获取,这是伪代码。
ByteArrayOutputStream baos = new ByteArrayOutputStream()
Bitmap bitmap = Bitmap.createBitmap( view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
// This converts the bitmap to a drawable
BitmapDrawable mDrawable = new BitmapDrawable(getResources(),bitmap);
或者,您可以使用该线程的另一个答案中概述的getDrawingCache()。