Android缩放图片的两种方法
2019-05-15 本文已影响0人
冷师傅_
缩放图片有两种手段:
1.缩放图片所在的ImageView.
2.缩放ImageView依附的Bitmap.
这两种方式共同套路就是
1.确定Bitmap的宽高,进而求得宽高比例.
2.ImageView根据Bitmap的宽高比确定自己的宽高.
- 缩放ImageView
Bitmap originalBitmap = Bitmap.decodeResouce(getResource(), R.drawable.demo_bitmap);
float bitmapWidth = originalBitmap.getWidth();
float bitmapHeight = originlBitmap.getHeight();
float bitmapRatio = bitmapWidth / bitmapHeight;
ImageView imgView = findViewById(R.id.img);
ViewGroup.LayoutParams params= imgView.getLayoutParams();
// 默认我们就设置图片和屏幕一样宽
params.width = Utils.getScreenSize();
params.height = params.width / bitmapRatio;
imgView.setLayoutParams(params);
// 算出图片的缩放比,以长度为基准
float scale = params.width / bitmap.width;
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
imgView.setScaleType(ScaleType.MATRIX);
imgView.setMatrix(matrix);
- 缩放Bitmap
Bitmap originalBitmap = Bitmap originalBitmap = Bitmap.decodeResouce(getResource(), R.drawable.demo_bitmap);
float bitmapRatio = bitmapWidth / bitmapHeight;
ImageView imgView = findViewById(R.id.img);
ViewGroup.LayoutParams params= imgView.getLayoutParams();
// 同样要确定ImageView的宽高
params.width = Utils.getScreenSize();
params.height = params.width / bitmapRatio;
imgView.setLayoutParams(params);
// 计算Bitmap的缩放比例
float bitmapScale = params.width / bitmapWidth;
Matrix matrix = new Matrix();
matrix.postScale(bitmapScale, bitmapScale);
// 设置缩放后的Bitmap
Bitmap scaleBitmap = Bitmap.create(originalBitmap,0,0,originalBitmap.getWidth(), originalBitmap.getHeight(),matrix, true);
imgView.setBitmap(scaleBitmap);