该工具类提供一下功能
- 获取屏幕宽高
- 对宽图片宽高进行等比缩放
代码如下:
package com.example.myapplication;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.util.DisplayMetrics;
import android.util.Log;
public class DeviceTools {
private static int[] deviceWidthHeight = new int[2];
public static Bitmap resizeBitmap(Bitmap bitmap){
if (bitmap != null){
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Log.i("info",width + " " + height);
Matrix matrix = new Matrix();
matrix.postScale(Config.scaleWidth,Config.scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap,0,0,width,height,matrix,true);
return resizedBitmap;
}else {
return null;
}
}
public static Bitmap resizeBitmap(Bitmap bitmap,int w,int h) {
if (bitmap != null) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = w;
int newHeight = h;
float scaleWidth = ((float)newWidth) / width;
float scaleHeight = ((float)newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth,scaleHeight);
Bitmap resizeBitmap = Bitmap.createBitmap(bitmap,0,0,width,height,matrix,true
);
return resizeBitmap;
}else {
return null;
}
}
public static int[] getDeviceInfo(Context context){
if ((deviceWidthHeight[0] == 0) && (deviceWidthHeight[1] == 0)){
DisplayMetrics metrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(metrics);
deviceWidthHeight[0] = metrics.widthPixels;
deviceWidthHeight[1] = metrics.heightPixels;
}
return deviceWidthHeight;
}
}
使用方法
emmm 想了想 还是有必要说说使用方法
工具类 顾名思义 就是说这个整个类 你可以把它理解为一种工具 就像你炒菜需要锅洗衣服需要盆一样 所以你需要在你的项目中创建一个新的类 (类名最好就是DeviceTools 这样和我提供的类的名字是一样的)然后将上面的代码复制进去 你在项目中就可以很方便的 通过调用这些函数来完成相应的事情了。