【问题标题】:Scaled Bitmap is randomly not displaying in the ImageView缩放位图随机不显示在 ImageView 中
【发布时间】:2015-12-21 06:41:10
【问题描述】:

我正在缩小MediaStore.ACTION_IMAGE_CAPTURE 拍摄的图像(尝试遵循所有更好的做法)

缩放图像分两步完成:

  1. 将捕获图像的完美样本解码为Bitmap
  2. 旋转和缩放位图以适合我的设备显示尺寸。

我真的不明白为什么有时图像可以完美地显示在图像视图中,而有时它只是空白!非常感谢任何帮助:-)

更新:我正在onActivityResult 中完成所有处理工作。不确定这种奇怪行为背后的原因?

为了更好地理解问题,我分享了一些关键的代码部分:

位图工厂选项

BitmapFactory.Options options = new BitmapFactory.Options();
options.inDither = false;
options.inPurgeable = true;
options.inInputShareable = true;
options.inJustDecodeBounds = false;
options.inTempStorage = new byte[32 * 1024];
options.inSampleSize = calculateInSampleSize(imageHeight, imageWidth, screenHeight, screenWidth);

样本大小计算

private int calculateInSampleSize(int imageHeight, int imageWidth, int reqHeight, int reqWidth)
{
    int inSampleSize = 1;
    if (imageHeight > reqHeight || imageWidth > reqWidth) {

        final int halfHeight = imageHeight / 2;
        final int halfWidth = imageWidth / 2;

        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }
    return inSampleSize;
}

解码位图并调整其大小

image = BitmapFactory.decodeFile(fileName, options);
Matrix matrix = new Matrix();

float scaleFactor = Math.min(1.0f, Math.max(width / imageWidth, height / imageHeight));
matrix.postScale(scaleFactor, scaleFactor);

Bitmap tempImage = Bitmap.createBitmap(image, 0, 0, image.getWidth(), image.getHeight(), matrix, false);
if( image.isMutable() || (image.getHeight()!=tempImage.getHeight() || image.getWidth()!=tempImage.getWidth()) ) {
    image.recycle();
}

imageView.setImageBitmap(tempImage);

【问题讨论】:

  • 我也面临同样的问题。您找到解决方案了吗?
  • 不,我还没有找到任何东西。仍在寻找此问题背后的任何帮助或线索。有什么发现欢迎分享。
  • 我当然会。我发现了很多this 线程。但这对我不起作用。

标签: java android image bitmap imageview


【解决方案1】:

我终于想通了,问题是整个布局正在 onResume() 中重新绘制,ImageView 也被重置。我调用了相同的方法,在 onResume() 而不是 onActivityResult() 方法中将此位图设置为 imageview,最终能够让它工作。

【讨论】:

  • 您能否进一步解释一下发生了什么?以前我没有在onResume() 方法中做任何事情。我尝试在 onResume 方法中更新图像视图图像。但这似乎对我不起作用。
  • 您是否将文件的 uri 保存在 onSaveInstanceState() 中并在 onRestoreInstanceState() 中再次使用它?我基本上在做的是,使用我保存在 onSaveInstanceState() 中的文件 uri 获取位图并将其设置为 imageview。这解决了我遇到的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多