Android - 在我以编程方式完成后缩放图像

标签 android background imagebutton image-scaling

奇怪的事情发生了——至少我不明白。

我有一张图像(宽:120 像素,高:63 像素)显示在一个 ImageButton 上。我拥有的该图像的唯一变体位于 drawable-hdpi 中(并且没有其他 drawable 目录)。 此图像和每个分辨率(密度)一切正常,Android 处理得很好。

但是,当我从相册中拍摄一张照片(例如一些非常大的照片)时,麻烦是将其缩放到按钮的尺寸(前面提到过,w: 120px h: 63px)并将该小图像设置为 ImageButton背景。

如果我在具有中等密度 (160) 的模拟器上进行测试,则没问题,但是在具有高密度按钮的设备上进行测试时,由于缩放后的图像看起来更小,因此会调整大小。

有没有人知道发生了什么,为什么在我缩放后图像的大小再次发生变化?

任何线索将不胜感激。

这是我用来调整图像大小的代码:

public static void resizeAndSaveImage(String pathToResize, int newWidth, int newHeight, FileOutputStream output) {
try {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 8;
    Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(pathToResize), null, options);
    if (bitmap != null) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
        output.close();
    }
} catch (Exception e) {
    // ...
}

维度参数传入如下:newWidth = 120, newHeight = 63。

最佳答案

为了实现您想要的效果,您需要使用密度无关像素 (dp) 而不是物理像素。从 here 读取:

The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, the baseline density assumed by the platform (as described later in this document). At run time, the platform transparently handles any scaling of the dp units needed, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: pixels = dps * (density / 160). For example, on 240 dpi screen, 1 dp would equal 1.5 physical pixels. Using dp units to define your application's UI is highly recommended, as a way of ensuring proper display of your UI on different screens.

为了更详细地解释为什么一张图片(相册照片)而不是图片资源会发生这种情况,您需要发布用于缩放的代码。

关于Android - 在我以编程方式完成后缩放图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4793641/

相关文章:

Android R.string ids 混合在多模块测试中

Android,删除自定义按钮边框

css - 破折号:数字小部件背景颜色

具有渐变和透明图像背景的 Android ImageButton[包含图像]

java - android onKeyDown onKeyUp 测量时间

java - 如何设置 doInbackground 在继续 mainActivity 之前完成其任务?

java - 无法获取Java中特定索引中的对象

android - 有没有简单的方法可以在 NativeScript/Angular 中为 IOS 和 Android 创建后台任务?

Android ImageButton 削减图标顶部

android - 按 ListViewItem 时谷歌地图的错误协调