起因是测试在测试过程中发现需要裁剪的图片看不到,但是还能继续裁剪。
所以就检查代码,发现了bitmap的width和Height有3000多。
然后试了下把图片改成300*300的就显示正常,
所以我们需要让图片根据大小不同,机器不同而改变图片的宽高
//设置分辨率
//1.获取系统分辨率
Resources resources = this.getResources();
DisplayMetrics dm = resources.getDisplayMetrics();
//2.获取图片分辨率
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;// 这个方式不会在内存创建一张图片,
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options); //此时返回的bitmap为null,但是option会保留一部分参数
//3.确定分辨率
int height = options.outHeight;
int width = options.outWidth;
if(options.outHeight>dm.heightPixels*1.5f){//当图片大小比屏幕大1.5倍的时候,直接以系统高度为高度
height = dm.heightPixels;
}
if (options.outWidth>dm.widthPixels*1.5f){
width = dm.widthPixels;
}
options.inJustDecodeBounds = false;
//4.创建合适的图片
bitmap = BitmapUtils.getBitmapFromFilePath(filePath,width,height);//resize图片
imageView.setImageBitmap(bitmap);
小米,和VIVO用手机拍完照片之后容易出这个问题,分辨率好高。
Bitmap工具函数
public static Bitmap getBitmapFromFilePath(String filePath, int width, int height) {
BitmapFactory.Options opts = null;
if (width > 0 && height > 0) {
opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, opts);
// 计算图片缩放比例
final int minSideLength = Math.min(width, height);
opts.inSampleSize = computeSampleSize(opts, minSideLength,
width * height);
opts.inJustDecodeBounds = false;
opts.inInputShareable = true;
opts.inPurgeable = true;
}
try {
return BitmapFactory.decodeFile(filePath, opts);
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
return null;
}
需要的话,可以考虑下改造Bitmap工具函数,减少代码量
网友评论