Sagan
Sagan

Reputation: 110

How to properly work with custom Views bitmap?

I'm extending a View where I display a bitmap, modified according to what I need.

I want to and most likely need to keep that bitmap in original size as a variable/object in case it gets zoomed-in so that it doesn't lose quality.

It seem to create OutOfMemory error when I use a lot of these custom views.

Now I am wondering how does one work with bitmaps in this case? How is it that ImageView handles it without a problem? How do they do this? And how do they preserve quality after the view gets resized dynamically?

Does anyone have any advice on this topic?

Thank you.

Upvotes: 0

Views: 156

Answers (1)

art
art

Reputation: 1332

To solve your problem you should store bitmaps in memory only for those of your views which are visible at the moment to save memory.

Also you should store a scaled down version of bitmap to save memory. BitmapFactory class has special mechanism for this. Use inJustDecodeBounds property of BitmapFactory.Options class to load width and height of the image without memory allocation for the image itself. Then calculate the value for inSampleSize property and use this property to load scaled down bitmap. Read this article for deeper description.

These problems (and others concerning showing images) are solved in third-party libraries: Glide, Fresco and others. These libs are widely used, so you can use them too. Also for example Glide supports extensions to modify images.

If you want to have an image view with zoom functionality there is the great library for this. It includes pinch to zoom, panning, rotation and animation support, and allows easy extension. The view even optionally uses subsampling and tiles to support very large images.

Upvotes: 1

Related Questions