0

我想在屏幕上以 2 x 2 网格格式显示 4 张图像。图片来自谷歌图片搜索,图片大小为 200 X 200

这是我扩展它们的方法。具有 4 个嵌套的 RelativeLayout 的 RelativeLayout,每个布局中都有 imageView。这就是我如何获得屏幕宽度来缩放图像。将内部布局参数的高度和宽度设置为 screenWidth/2,然后缩放图像。

这就是我为获取特定屏幕的图像高度和宽度所做的工作。例如,如果屏幕宽度为 550,那么我的图像尺寸将为 275 x 275。

public static int getOptionWidth(Context context) {
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    return metrics.widthPixels;
}

optionWidth = (getOptionWidth(context) / 2)

这是用于未缩放的位图

public static Bitmap resourceDecoder(byte[] imgBytes, int destWidth, int destHeight) {
    Options options = new Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(imgBytes, 0, imgBytes.length, options);
    options.inJustDecodeBounds = false;


    float srcAspect = (float) srcWidth / (float) srcHeight;
    float dstAspect = (float) dstWidth / (float) dstHeight;

        if (srcAspect > dstAspect) {
            options.inSampleSize = srcHeight / dstHeight;
        } else {
            options.inSampleSize = srcWidth / dstWidth;
        }
    Bitmap unscaledBitmap = BitmapFactory.decodeByteArray(imgBytes, 0, imgBytes.length, options);

    return unscaledBitmap;
}

这将是我的目标宽度和高度,因为我需要方形图像。我已经实现了获取源矩形(getSrcRect)和获取目标矩形(getDstRect)的基本方法

Rect srcRect = getSrcRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(), dstWidth, dstHeight);
Rect dstRect = getDstRect(unscaledBitmap.getWidth(), unscaledBitmap.getHeight(), dstWidth, dstHeight);
Bitmap scaledBitmap = Bitmap.createBitmap(dstRect.width(), dstRect.height(), Config.ARGB_8888);
Canvas canvas = new Canvas(scaledBitmap);
canvas.drawBitmap(unscaledBitmap, srcRect, dstRect, new Paint(Paint.FILTER_BITMAP_FLAG));

return scaledBitmap;

这工作正常,结果如预期(在 hdpi、xhdpi 和 mdpi 上测试)。但现在我很困惑,因为我没有使用 dxtopx 或 pxTodX 转换。我错过了什么吗?虽然结果符合预期,但我并不担心这种方法。我不知道我应该使用 pxToDx 还是反之亦然。如果我这样做,它将如何影响我的结果以及我应该如何使用这些。

4

1 回答 1

0

您不必为此使用 PX 到 DP 转换,因为您已经使用 getOptionWidth(context) 设置了相对于屏幕宽度的所有大小变量。

于 2013-04-02T12:07:57.193 回答