我有一个简单的布局,我想要一个背景图片。首先,我尝试将背景图像放在xml中,但是有很多滞后。
所以我跟着Set image through AsyncTask但仍然没有运气。
图像分辨率为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) {}
}
}
答案 0 :(得分:1)
您的图片尺寸很大。将图像设置为背景的问题是图像的大小而不适合分辨率。我有同样的问题。经过搜索和测试很多方法,我发现滑行是一个很好的库来设置图像。使用此库,您的设备大小并不重要。滑行会设置它。
来自drawable的set image,你可以像这样编码:
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大小
答案 1 :(得分:0)
重要的是要理解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));
}
...
}