android-把96dpi,72dpi的图片改成200dpi的

时间:2025-01-27 09:21:39

中有属性:

inTargetDensity——Bitmap最终的像素密度

但是测试发现inTargetDensity即使设置成480也没起作用。

 /**
     * 使用inSampleSize、inScaled、inDensity、inTargetDensity对图片进行缩放
     * <p>
     * targetDensity使用屏幕的dpi密度,如480
     *
     * @param context
     * @param imageView 缩放后的图片显示
     */
    public static void resizeBitmap(Context context, ImageView imageView) {
        try {
             options = new ();
             = true;
            (().getAssets().open(""), null, options);

            int targetDensity = ().getDisplayMetrics().densityDpi;    //华为nova 2 plus 手机测试为480

            DisplayMetrics dm = new DisplayMetrics();
            ((AppCompatActivity) context).getWindowManager().getDefaultDisplay().getMetrics(dm);

            int x = ;
            int y = ;
             = calculateInSampleSize(options, x, y);

            double xSScale = ((double) ) / ((double) x);
            double ySScale = ((double) ) / ((double) y);

            double startScale = xSScale > ySScale ? xSScale : ySScale;

             = true;
             = (int) (targetDensity * startScale);
            options.inTargetDensity = targetDensity;
             = false;
            Bitmap bitmap = (().open(""), null, options);
            (context, bitmap);
            (bitmap);
        } catch (IOException e) {
            ();
            (TAG, ());
        }
    }

    public static int calculateInSampleSize( options,
                                            int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = ;
        final int width = ;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and
            // keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }