项目遇到实现图片等比例缩这个需求时,很容易想到如下代码:
int bwidht=bmp.getWidth();
int bheight=bmp.getHeight();
float sx= (float) ((dewidth0.1)/(bwidht0.1));
Matrix matrix = new Matrix();
matrix.postScale(sx,sx); //长和宽放大缩小的比例
final Bitmap newb = Bitmap.createBitmap(bmp,0,0,bwidht, bheight,matrix,true );
这样很容易实现图片等比例缩放,却隐藏一个出现oom的隐患Bitmap.createBitmap(bmp,0,0,bwidht, bheight,matrix,true )容易出现oom,所以这中实现方式不可取的。那么是怎么解决呢?别急!!!
解决办法如下:设置 ImageViewde的属性android:adjustViewBounds="true"和android:scaleType="fitXY"即可实现图片等比例缩放。
<ImageView android:id="@+id/item_recom_joke_iv" android:layout_width="match_parent" android:layout_height="wrap_content" android:adjustViewBounds="true" android:scaleType="fitXY" android:src="@drawable/default_icon" />
把android:adjustViewBounds="true"和android:scaleType="fitXY"设置一就实现图片等比缩放,就那么简单就解决了。可是一会,产品找过了说在红米1s 4.2.2会出现变形,宽正常放大,高没有没有正常放大反而缩小。拿着那台图片出现变形的红米,研究半天也没有找到原因变形的原因。只好强制设置ImageView高,这样才解决了这问题。我用的Glide,代码如下:
// 图片等比加载 Glide.with(Global.getContext()).load(url).asBitmap().diskCacheStrategy(DiskCacheStrategy.ALL).into(new BitmapImageViewTarget(imageView) {
@Override
protected void setResource(Bitmap resource) {
super.setResource(resource);
int width = resource.getWidth();
int height = resource.getHeight();
//获取imageView的宽
int imageViewWidth= imageView.getWidth();
//计算缩放比例
float sy= (float) (imageViewWidth* 0.1)/(float) (width * 0.1);
//计算图片等比例放大后的高
int imageViewHeight= (int) (height * sy);
ViewGroup.LayoutParams params = imageView.getLayoutParams();
params.height = imageViewHeight;
imageView.setLayoutParams(params);
}
});
参考:
http://www.jianshu.com/p/f8ad3bbb002b
http://blog.csdn.net/qq_34995257/article/details/52414944