When a user clicks a button, i keep switching the background of a layout like this in Activity code:
...
mylayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.img1));//On First click
mylayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.img2));//On Second Click
mylayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.img10));//On 10th Click
...
mylayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.img1));//On 11th Click 1st image again and so on.
I have 10 images which i keep rotating.
Soon, it causes OutOfMemory exception. What am i doing wrong?
If it matters in my manifest file i have:
android:minSdkVersion="11"
android:targetSdkVersion="17" />
EDIT 1
Average size of the image is: 50K
Average dimension of the image is: 600x450
All images img1, img2 etc.. are jpeg images
Solution Update
Reducing image dimensions to 300x200 resolved the issue. The memory requirements went down significantly by this single change.
It might be happening because your image resources are in drawable folder; which is equivalent to drawable-mdpi. And your device might be something other than mdpi.
So, either provide images for all the screed densities you are gonna support. Or, put images in drawable-nodpi, so your images will not be resized. Hence no OutOfMemoryException.
Referred from here
Use Bitmap.recycle() if you can change your Drawable with Bitmap.
Hope This will help
Each bitmap with dimension 600x450 has size of 600*450*4 = 1 080 000 bytes (1 MB) in RAM.
You should load so large bitmaps in another way:
Bitmap bitmap = BitmapFactory.decodeResource(resources, R.drawable.img1);
myLayout.setBackgroundDrawable(new BitmapDrawable(resources, bitmap));
And before changing background of the view you have to do
Drawable background = myLayout.getBackground();
if (background != null && background instanceof BitmapDrawable) {
myLayout.setBackgroundDrawable(null);
BitmapDrawable bd = (BitmapDrawable) background;
bd.getBitmap().recycle();
}
I dont think changing background layout so frequently is a good idead. I suggest that you could use RelativeLayout with an ImageView as first item. Then everytime you need to change your background, you can change your ImageView with some cached library such as: Universal Image Loader
Related
My app is using way too much memory, and I'm not too sure why. I'm making a solitaire game. I'm using a chained ConstraintLayout of 10 equal width RelativeLayouts (1 for each stack of cards). [I know I can use other Viewgroups].
My app is using ~15mb memory, until I do this;
public void DrawCardsMat0()
{
RelativeLayout mat = (RelativeLayout) findViewById(R.id.PLAY_Mat0);
mat.removeAllViews();
RelativeLayout rl = new RelativeLayout(this);
for (PlayingCard playingCard : Stack0.Cards)
{
ImageView myImg = GetCardImage(playingCard);
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(CardWidth, CardHeight);
lay.setMargins(0, playingCard.UI_MarginTop, 0, 0);
mat.addView(myImg, lay);
}
}
and
public ImageView GetCardImage(PlayingCard playingCard)
{
ImageView myImg = new ImageView(this);
// a simple switch is used to here to pick the drawable. Removed as there's 52 cards)
myImg.setImageResource(R.drawable.s1);
return myImg;
}
CardWidth and CardHeight are ints (150 and 210, roughly. Pixels).
This draws FIVE cards, and each .jpg is ~60KB (yes, KB). This results in 60MB of memory usage. 10 cols == 600mb of memory (I assume, as it's OOM before then).
The images are in a RelativeLayout, and are placed on top of each other. MarginTop is used to "stack" them.
thanks in advance
--- update 1 ---
I'm now using a 46KB bmp image.
Creating 5 ImageViews (one stack's worth) in XML (and don't call anything in code) uses ~50mb memory. Tested using a LinearLayout.
Creating same images in-code uses same amount of memory.
--- update 2 ---
If I create a new Activity, with just a simple LinearLayout and 5 ImageViews, and no java code, it still uses ~50MB memory.
When working with bitmaps, you should always be careful. I'll describe the most important points and considering them, you can change the way work with card images is organized.
Bitmap in memory always exists in uncompressed format, so its size will be different from the size of your .jpg/.png/.webp/.[whatever compressed format]. The actual size depends on the Bitmap.Config, but by default Android will use ARGB_8888 (1 byte for alpha channel, 1 byte for each of R/G/B channels). You can roughly estimate the size in memory by saving the image in .bmp format.
When you use <bitmap> tag with drawable, it means in runtime bitmap will be wrapped in BitmapDrawable. As you can see, by default bitmap will be loaded as-is, taking original size.
When you call myImg.setImageResource(R.drawable.s1) it means that bitmap will have the same size as before in memory, it will be just scaled by using the matrix depending on the size of ImageView and scaleType you specified.
Considering that, probably you may want to load downscaled bitmap to the memory, depending on the view size. You can do that by using BitmapFactory class instead. I suggest you to read these 2 articles in order to understand how Android is working with bitmaps: Managing Bitmap Memory and Loading Large Bitmaps Efficiently.
You may also consider using some image library, like Picasso or Glide which can load downscaled bitmap depending on the size of ImageView. You can also try to use Fresco which keeps bitmap outside of JVM heap.
If you have such possibility, better to have cards in SVG format. Then you can work with vectors instead of having bitmap, which is much more memory-friendly (because SVG is just a set of instructions on how to draw). However in case of really complex SVG file you can hit another problem - it will take a lot of time to draw it. Check this article on how to use it with ImageView.
This situation I have met in Android and still can't find any solution.
I have an ImageView display by these code:
BitmapDrawable value = ...;
imageView1.setImageDrawable(value);
Then I use imageView2 to display the same image in Drawable:
imageView2.setImageDrawable(value);
And ops,... the image in imageView1 auto scale and become bigger than the older. (imageView2 is bigger than imageView1).
Is there anyone saw this situation before?
Drawables are immutable, so the one bitmap is getting scaled and then shown by both ImageViews.
To get a different (unshared) version for the second one, try:
imageView2.setImageDrawable(value.mutate());
I am using a viewpager to swipe amongst fragments in my app. I define the background in the XML, so
android:background="#drawable/bg_final"
If I use a simple background color, my app works very smooth. If I use it with this background image, fps decreases and my app becomes only passable. It is not slow, just not so smooth, however on weaker devices it could work laggy. Is it a bad way to apply a background image? The whole image is a 480x800 png with the size of 14.7kB. What might be the problem?
(the backgrounds of the fragments are transparent, the viewpager is in a main.xml which has its background with this image)
There are lots of answers out there that point to pre-scaling your bitmap. This is very imporant and you should do it if you can, however after trying several different things, the biggest performance gain I experienced was to create a view and override the onDraw method.
The class could be as simple as this:
public class DTImageView extends View {
public Bitmap imageBitmap;
public DTImageView(Context context) {
super(context);
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(imageBitmap != null)
canvas.drawBitmap(imageBitmap, 0, 0, null);
}
}
Invoke the code using a prescaled bitmap:
DTImageView bgImageView = new DTImageView(context);
bgImageView.imageBitmap = Bitmap.createScaledBitmap(bitmap,width,height,true);
At this point you can add this view to the view hierarchy where it belongs. In my case, my view hierarchy had a bgImage, a middle ground where all the other functionality happened, and fgImage.
Use the android sdk tool Hierarchy Viewer to profile the app and see how fast each view is taking to draw. My app spent 30-40ms drawing the bgImage and fgImage. Pre-scaling and overriding onDraw reduced that 30-40ms to about 1.5ms.
Here is a screenshot of the Draw performance for one of my views before and after:
BEFORE:
AFTER:
I'm a bit late, but this just bit me, and when running the GPU debugger, I noticed that the system scaled up my image! I had a 1920x1080 image, and it showed up as a 3780x6720 texture!
Ideally, you should have textures for each density in the respective folder (res/drawable-mdpi, res/drawable-hdpi, etc).
However, if you think your one texture is fine, put it into res/drawable-nodpi, not res/drawable. If you put it into res/drawable-nodpi, the system won't scale it up based on the dpi.
In my case, it changed a simple UI from 10fps on a Pixel XL to the full frame rate of 60fps.
I had a background image, not big in size, but with weird dimensions - therefore the stretching and bad performance. I made a method with parameters Context, a View and a drawable ID(int) that will match the device screen size. Use this in e.g a Fragments onCreateView to set the background.
public void setBackground(Context context, View view, int drawableId){
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), drawableId);
int width = Resources.getSystem().getDisplayMetrics().widthPixels;
int height = Resources.getSystem().getDisplayMetrics().heightPixels;
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
BitmapDrawable bitmapDrawable = new BitmapDrawable(context.getResources(), bitmap);
view.setBackground(bitmapDrawable);
}
The reason for this could be that the image is being stretched, and Android has performance issues with stretching background images.
Instead, you should either replace the background image with either a background color or see this answer to have the image repeat instead of stretch.
I had the same problem and I resolved it by using this method:
Add your image to the mipmap folder which is located under the res directory. It will add the image according to it's density.
Create add only one background image with size 1080x1920 and put it in drawable-nodpi folder and that solved this problem
This question is related with Do we have to explicitly recycle the bitmap if we don't need it?.
There is an ImageView have a drawable, when user clicks a button, it will assign a new drawable to the ImageView.
Do we have to destroy the old drawable belongs to the ImageView, and how?
Drawable oriDrawable = imageView.getDrawable()
// set callback to null
oriDrawable.setCallback(null);
// get the bitmap and recycle it
((BitmapDrawable)oriDrawable).getBitmap().recycle();
Is the code above correct? What's the best solution?
You could try using something like:
Drawable drawable = imageView.getDrawable();
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap bitmap = bitmapDrawable.getBitmap();
bitmap.recycle();
}
Where imageView is your ImageView.
Original answer here.
Is this just a general question or are you running out of memory? I would not make this optimisation until you really have a problem.
In general if you are loading bitmaps from drawable folders that are not large (large as in megabytes) then you should not really run into a problem.
First you need to make sure the assets you are loading are optimal for where you display them, for example there is no point in setting an ImageView to an image thats 1024 x 1024 in size if the area you display the image is a size of 64x64.
Breaking the bitmap budget is usually caused by loading in images of an unknown size or just simply getting the image sizes wrong as described above, swapping an ImageView frequently will generally not give you an issue with optimal sized images.
There is a great article in Android Training that covers loading bitmaps optimally http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
Hope that helps
I updated my build to build against Android 1.6, and now my bitmaps are scaled down on high density screens. I do NOT want this behavior. I gave this a shot:
http://blog.tomgibara.com/post/190539066/android-unscaled-bitmaps
but the images are STILL scaling, that is UNLESS I set them to a specific height & width. If I use wrap_content they are scaled down.
I have an image loader using the unscaled bitmap loader to create a drawable like so:
Bitmap bm = UnscaledBitmapLoader.loadFromResource(imageBufferInputStream);
drawable = new BitmapDrawable(bm);
which I later assign to an ImageView like so:
imageView.setImageDrawable( copyBitmapDrawable( (BitmapDrawable) drawable) );
In order to have an image not scaled when loading it from a resource (e.g. with BitmapFactory.decodeResource) you have to locate it in res/drawable-nodpi instead of the usual drawable, drawable-ldpi and so on.
Using
new BitmapDrawable(this.getResources(), bmp);
instead of
new BitmapDrawable(bmp);
should solve the issue.
Wrapping the bitmap with a Drawable is the problem. The Drawable scales the Bitmap. Instead of using a Drawable, assign the Bitmap to the ImageView directly using imageView.setImageBitmap(Bitmap).
Use ImageView.ScaleType. The CENTER constant preforms no scaling, so I guess that's what you are looking for.
By the way, do you use pixels or dips as size units? Using dips (density-independent-pixels) is a means of standardizing display on multiple resolutions. You'll find a couple of tips here.