一、获取屏幕的宽高:
1.通过getWidth(),getHeight()获取,不过该方法已被弃用:
WindowManager windowManager = getWindowManager();
screenWidth = windowManager.getDefaultDisplay().getWidth();
screenHeight = windowManager.getDefaultDisplay().getHeight();
2.通过getSize(point),该方法在api13时引入:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
windowManager.getDefaultDisplay().getSize(point);
screenWidth = point.x;
screenHeight = point.y;
Log.e(TAG, "width : " + width + ", height : " + height);
}
二、截取图片某一部分并按屏幕宽高比放大:
private void displayBitmap()
{
try {
InputStream inputStream = getAssets().open("chemo.jpg");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(inputStream, null, options);
int width = options.outWidth;
int height = options.outHeight;
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
originalImgView.setImageBitmap(bitmap); // 显示原图
BitmapRegionDecoder bitmapRegionDecoder = BitmapRegionDecoder.newInstance(inputStream, false);
// 截取图片某部分
bitmap = bitmapRegionDecoder.decodeRegion(new Rect(width/3 - 100, height/3 - 100, width/3 + 100, height/3 + 100), options);
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
Log.e(TAG, "bitmapWidth : " + bitmapWidth + ", bitmapHeight : " + bitmapHeight);
int xScale = screenWidth/bitmapWidth;
int yScale = screenHeight/bitmapHeight;
// 利用矩阵缩放截取出来的那部分图片
Matrix matrix = new Matrix();
matrix.postScale(xScale, yScale);
Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmapWidth, bitmapHeight, matrix, true);
showImgView.setImageBitmap(resizeBmp);
} catch (IOException e) {
e.printStackTrace();
}
}
效果图: