Android 高效加载位图-开始时显示纯色
我使用了《开发者指南》中的说明,并按照该教程中的说明逐点操作 您可能知道,这是我使用的代码:Android 高效加载位图-开始时显示纯色,android,image,bitmap,imageview,Android,Image,Bitmap,Imageview,我使用了《开发者指南》中的说明,并按照该教程中的说明逐点操作 您可能知道,这是我使用的代码: public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth,int reqHeight){ //Raw height and width of the Image final int height = options.outHeight; final int width =
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth,int reqHeight){
//Raw height and width of the Image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height>reqHeight || width>reqWidth) {
final int heightratio = Math.round((float)height / (float)reqHeight);
final int widthRatio = Math.round((float)width / (float)reqWidth);
inSampleSize = heightratio < widthRatio ? heightratio : widthRatio;
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,int reqWidth,int reqHeight){
//first decode with inJustdecodeBounds = true to check dimensions.
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
//Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
//Decode bitmap with inSampleSize
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
现在的问题是,每次加载onCreate()时,第一次单击的图像将仅显示图像的纯色,而不是整个图像,如下所示:
从下一次单击开始,无论是在同一个图像上还是在下一个图像上,代码都可以正常工作,如下所示:
在活动重新启动之前,其他一切都正常工作。如果我们重新启动或恢复此活动,同样的事情也会发生
那么,出了什么问题?请澄清:
确保不要在onresume/onstart方法中调用handler start方法,也确保在方向发生变化时不会再次调用oncreate我刚刚解决了这个问题并自己解决了,实际上这是安卓加载图像的一个小检查:
@Override
public void run() {
// TODO Auto-generated method stub
learn_full_iv.setVisibility(View.VISIBLE);
learn_full_iv.startAnimation(anim);
switch (id) {
case R.id.a:
//learn_full_iv.setImageResource(R.drawable.aeroplane);
learn_full_iv.setImageBitmap(decodeSampledBitmapFromResource(
getResources(), R.drawable.aeroplane, learn_full_iv.getWidth(), learn_full_iv.getWidth()));
Toast.makeText(getApplicationContext(), "Width : " + learn_full_iv.getWidth() + "Height : " + learn_full_iv.getHeight(), Toast.LENGTH_SHORT).show();
playSound(1, 2);
break;
...........
上面代码中的问题是,我只是在run方法的开始启用ImageView“learn_full_iv”,默认情况下宽度和高度为“0”,因为ImageView上仍然没有设置图像
因此,如果我们打电话:
learn_full_iv.setImageBitmap(decodeSampledBitmapFromResource(
getResources(), R.drawable.aeroplane, learn_full_iv.getWidth(), learn_full_iv.getWidth()));
在这种情况下,宽度和高度将为零,因此,只会显示该图像中的一种颜色。因此,我使用方法将屏幕的宽度和高度作为整数值获取,并在上述位图解码方法中将其传递到相应的宽度和高度部分
就是这样,因为现在我们将宽度和高度作为值,现在将显示位图
简单 我也掉进了那个坑里。谢谢你帮我走出困境:)
learn_full_iv.setImageBitmap(decodeSampledBitmapFromResource(
getResources(), R.drawable.aeroplane, learn_full_iv.getWidth(), learn_full_iv.getWidth()));