我正在从URL加载图像并在运行时显示在imageview上。
我的问题是有时我的图像仅显示图像的半部分,图像的其余部分显示为白色。网上已经阅读了很多帖子,但没有一个人帮助过我...
请为同样和真正的事业提供一个好的解决方案。
这是我用来创建位图的代码。
public static Bitmap getBitmapFromCard(String path, int reqWidth,
int reqHeight) {
try {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
} catch (OutOfMemoryError e) {
System.gc();
System.gc();
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = 3;
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
}
计算 - InSampleSize
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of 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;
}
答案 0 :(得分:0)
您可以使用第三方库进行图像加载,如通用图像加载程序或Picasso等。下面是使用毕加索加载图像的代码,
void loadimage(String url, ImageView target) {
Picasso.with(sContext).load(url)
}
您可以在库中使用许多自定义功能,
void loadimage(String url, ImageView target) {
Picasso.with(sContext)
.load(url)
.placeholder(sContext.getResources().getDrawable(R.drawable.ic_launcher))
.error(sContext.getResources().getDrawable(R.drawable.ic_error))
.into(target);
}