Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Canvas to Drawable

Tags:

android

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); 

Is there any way to convert mCanvas to a Drawable? My goal is to generate drawables with a certain shape and color.

Thanks

like image 568
Johan Avatar asked Feb 20 '23 23:02

Johan


1 Answers

For simple shapes like your circle, I'd think a Shape Drawable would be easier. For more complicated things, just create a Bitmap for your Canvas to use, then create the Canvas and draw into it, then create a Drawable from your Bitmap. Something like:

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);

To be perhaps somewhat pedantic (and hopefully increase your understanding), a Canvas just hosts the "draw" calls and draws into a Bitmap that you specify. This means:

  1. Your example code doesn't do much, since you didn't construct your Canvas with a Bitmap or call setBitmap() on it.
  2. You're not converting your Canvas to a Drawable, you're constructing a Drawable from the Bitmap your Canvas calls draw into.
like image 124
Darshan Rivka Whittle Avatar answered Mar 08 '23 04:03

Darshan Rivka Whittle