【问题标题】:Android - scaling image after I did it programmaticallyAndroid - 我以编程方式完成后缩放图像
【发布时间】:2011-01-25 12:43:10
【问题描述】:

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

我有一张图片(宽:120 像素,高:63 像素),显示在一个 ImageButton 上。我拥有的该图像的唯一变体放在 drawable-hdpi 中(并且没有其他可绘制目录)。 这张图片和每个分辨率(密度)都很好,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。

【问题讨论】:

  • 将 api 设置为 1.5,这将阻止 android 调整大小,但意味着您必须这样做。

标签: android background imagebutton image-scaling


【解决方案1】:

为了达到您想要的效果,您需要使用与密度无关的像素 (dp) 而不是物理像素。读自here:

与密度无关的像素是 相当于一个物理像素 160 dpi 屏幕,基线密度 由平台假设(如所述 稍后在本文档中)。在运行时, 该平台透明地处理任何 缩放所需的 dp 单位,基于 关于屏幕的实际密度 采用。 dp 单位转换为 屏幕像素很简单:像素 = dps *(密度/160)。例如,在 240 dpi 屏幕上,1 dp 等于 1.5 物理像素。使用 dp 单位 高度定义应用程序的 UI 推荐,作为确保 在不同的地方正确显示您的 UI 屏幕。

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

【讨论】:

  • 我添加了用于调整大小的代码 sn-p - 希望对您有所帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-26
  • 1970-01-01
  • 2011-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多