导致延迟和跳帧的背景图像

Background image causing lag and frame skipping

我有一个简单的布局,我想要一个背景图片。首先,我尝试通过 xml 放置背景图像,但延迟很大。

所以我关注了 ,但仍然没有运气。

图片分辨率为 1131 X 1800,大小为 369kb。

I/Choreographer: Skipped 33 frames!  The application may be doing too much work on its main thread.
I/Choreographer: Skipped 37 frames!  The application may be doing too much work on its main thread.
I/Choreographer: Skipped 34 frames!  The application may be doing too much work on its main thread.
I/Choreographer: Skipped 34 frames!  The application may be doing too much work on its main thread.
I/Choreographer: Skipped 34 frames!  The application may be doing too much work on its main thread.

Java 文件

public class MainActivity extends flights{
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new LoadDrawable().execute();
}

private class LoadDrawable extends AsyncTask<Drawable, Void, Drawable> {
    @Override
    protected Drawable doInBackground(Drawable... params) {
        //Loading the drawable in the background
        final Drawable image = getResources().getDrawable(R.drawable.as);
        //After the drawable is loaded, onPostExecute is called
        return image;
    }

    @Override
    protected void onPostExecute(Drawable loaded) {
        //Hide the progress bar
        //ProgressBar progress = (ProgressBar) findViewById(R.id.progress_bar);
        //progress.setVisibility(View.GONE);
        //Set the layout background with your loaded drawable
        RelativeLayout layout = (RelativeLayout) findViewById(R.id.root);
        layout.setBackgroundDrawable(loaded);
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onProgressUpdate(Void... values) {}
}

}

你的图片太大了。将图像设置为背景的一个问题是图像大小而不适合分辨率。我有同样的问题。经过搜索和测试多种方法,我发现 glide 是一个很好的设置图像的库。使用这个库,你的设备大小并不重要。滑行将设置它。

要从您的可绘制对象中设置图像,您可以这样编码:

 Glide.with(this).load(R.drawable.backtwo).asBitmap().into(new SimpleTarget<Bitmap>(size.x, size.y) {
            @Override
            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                Drawable drawable = new BitmapDrawable(resource);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    iv_background.setBackground(drawable);
                }
            }
        });

另一种方法是针对不同的设备屏幕使用不同的图像分辨率。这种方法的缺点是增加了 apk 的大小

了解 onPostExecute() 发生在主线程上很重要,因此可能会导致您所看到的情况(但您在这里没有解决方法)。

关于你的问题,图片不大,应该不会出现这种问题;但是,如果将其替换为较小的图像,可能值得测试会发生什么(顺便说一句,最好使用分辨率均匀的图像 - 1131 在这里是一个错误的数字)。

另一种选择是在异步任务中解码位图(这很耗时)-

private class LoadDrawable extends AsyncTask<Drawable, Void, Drawable> {
    @Override
    protected Drawable doInBackground(Drawable... params) {
        return new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.as)); 
    }
    ...
}