Say I have a somewhat large (i.e. not fit in most phones’ memory) bitmap on disk. I want to draw only parts of it on the screen in a way that isn’t scaled (i.e. inSampleSize == 1)
Is there a way to load/draw just the part I want given a Rect specifying the area without loading the entire bitmap content?
I’m quite confident this is possible since you can load a really large bitmap file into an
ImageViewwithout problems so there must be some sort of a built-in way to handle large bitmaps… and after a few attempts, I’ve found a solution:Instead of loading the entire bitmap and manually draw it yourself, load it as a
Drawableinstead:I’m using a resource file but since you can use
Drawable.createFromStreamto load image from anyInputStream, it should works with arbitrary bitmap.Then, use the
Drawable.drawmethod to draw it onto the desired canvas like so:As in the above case, You can also scale and translate the bitmap as well by manipulating the drawable’s bounds and only the relevant parts of the bitmap will be loaded and drawn onto the
Canvas.The result is a pinch-zoomable view from just one single 200KB bitmap file. I’ve also tested this with a 22MB PNG file and it still works without any
OutOfMemoryErrorincluding when screen orientation changes.