android 按比例缩放图片(适屏)

private Bitmap reSize(Bitmap bitmaporg) {
    int widthold = bitmaporg.getWidth();//eg:1024
    int heightold = bitmaporg.getHeight();//eg:819
    //获取屏幕的宽高
    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    int screenWidth = dm.widthPixels;  //eg:1440
    int screenHeigh = dm.heightPixels;  //eg:2392
    float density = dm.density;  // 密度(0.75 / 1.0 / 1.5 //eg: 1dp=3.5px
    //int densityDpi = dm.densityDpi;  // 密度DPI120 / 160 / 240    float scale = (float) screenWidth / ((density + 0.2f) * widthold);
    Matrix matrix = new Matrix();
    if (scale < 1) {
        //将大图缩小至适屏
        float scaleWidth = (float) scale;
        float scaleHeight = (float) scale;
        matrix.postScale(scaleWidth, scaleHeight);
    } else {
        float scaleWidth = 1;
        float scaleHeight = 1;
        matrix.postScale(scaleWidth, scaleHeight);
    }

    Log.d("Main", "screenWidth:" + screenWidth);
    Log.d("Main", "screenHeight:" + screenHeigh);
    Log.d("Main", "widthold:" + widthold);
    Log.d("Main", "heightold:" + heightold);


    Bitmap bitmapnew = Bitmap.createBitmap(bitmaporg, 0, 0, widthold, heightold, matrix, true);
    int widtnew = bitmapnew.getWidth();
    int heightnew = bitmapnew.getHeight();
    Log.d("Main", "widthnew:" + widtnew);
    Log.d("Main", "heightnew:" + heightnew);
    return bitmapnew;

}

你可能感兴趣的:(Android)