android背景图像减慢应用程序 [英] android background image slows down app

查看:20
本文介绍了android背景图像减慢应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 viewpager 在我的应用程序中的片段之间滑动.我在 XML 中定义背景,所以

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"

如果我使用简单的背景颜色,我的应用程序会非常流畅.如果我将它与这个背景图像一起使用,fps 会降低,我的应用程序变得只能通过.它并不慢,只是不那么流畅,但是在较弱的设备上它可能会滞后.应用背景图像是一种不好的方法吗?整个图像为 480x800 png,大小为 14.7kB.可能是什么问题?

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?

(片段的背景是透明的,viewpager 位于 main.xml 中,该文件的背景与此图像有关)

(the backgrounds of the fragments are transparent, the viewpager is in a main.xml which has its background with this image)

推荐答案

有很多答案都指向预缩放位图.这非常重要,如果可以的话,您应该这样做,但是在尝试了几种不同的方法之后,我体验到的最大性能提升是创建一个视图并覆盖 onDraw 方法.

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.

这个类可以这么简单:

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);

此时您可以将此视图添加到它所属的视图层次结构中.在我的例子中,我的视图层次结构有一个 bgImage、一个所有其他功能发生的中间地带,以及 fgImage.

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.

使用 android sdk 工具 Hierarchy Viewer 来分析应用并查看每个视图的绘制速度.我的应用程序花了 30-40 毫秒绘制 bgImage 和 fgImage.预缩放和覆盖 onDraw 将 30-40 毫秒减少到大约 1.5 毫秒.

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.

以下是我的一个视图前后的 Draw 性能截图:

Here is a screenshot of the Draw performance for one of my views before and after:

之前:

之后:

这篇关于android背景图像减慢应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆