Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
351 views
in Technique[技术] by (71.8m points)

android background image slows down app

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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: Using setImageBitmap instead of overriding onDraw.

AFTER: Using the above DTImageView which simply overrides OnDraw


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...