119

I'd like to create an empty bitmap and set a canvas to that bitmap and then draw any shape on the bitmap.

0xCursor
  • 2,242
  • 4
  • 15
  • 33
Sunil Pandey
  • 7,042
  • 7
  • 35
  • 48

2 Answers2

225

This is probably simpler than you're thinking:

int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

Here's the official documentation on the topic: Custom Drawing

bigstones
  • 15,087
  • 7
  • 65
  • 82
  • If I create that within a seperate class, how would I reference the bitmap in another class. For example: Bitmap text = BitmapFactory.decodeResource(mContext.getResources(), What to put here?); I need a textView within an opengl live wallpaper. Thanks in advance – Steve C. May 07 '13 at 21:47
  • Hi @bigstones I am following your code for creating bitmap in onSizeChanged() when I am creating bitmap I am getting OutOfMemoryError please see this http://stackoverflow.com/questions/24303759/outofmemoryerror-when-creatingbitmp – user123456 Jun 23 '14 at 05:25
  • How can this be done in another thread while using SurfaceView? – Zach H Jun 24 '14 at 00:20
  • just make sure x and y are not zero else it will throw exception illegal Argument – Fazal Jarral Sep 26 '20 at 16:39
  • wow, this hasn't changed in 11 years?! – bigstones Apr 27 '22 at 16:44
-6

Do not use Bitmap.Config.ARGB_8888

Instead use int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_4444; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

ARGB_8888 can land you in OutOfMemory issues when dealing with more bitmaps or large bitmaps. Or better yet, try avoiding usage of ARGB option itself.

user2903200
  • 708
  • 2
  • 7
  • 19
  • 14
    ARGB_4444 is deprecated now (http://developer.android.com/reference/android/graphics/Bitmap.Config.html#ARGB_4444) – Allen Sep 21 '14 at 23:36