ChatGPT解决这个技术问题 Extra ChatGPT

Creating an empty bitmap and drawing though canvas in Android

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


b
bigstones

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


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
Hi @bigstones I am following your code for creating bitmap in onSizeChanged() when I am creating bitmap I am getting OutOfMemoryError please see this stackoverflow.com/questions/24303759/…
How can this be done in another thread while using SurfaceView?
just make sure x and y are not zero else it will throw exception illegal Argument
wow, this hasn't changed in 11 years?!
u
user2903200

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.