为什么位图为空

时间:2014-11-26 03:56:05

标签: android

我正在按照教程here与其他应用和自定义SurfaceView拍照。

使用SurfaceView拍照时,图片拍摄成功(我退出了我的应用程序,看到结果图像文件确实存在于文件管理器中,图像内容正确。),但图片无法在我的应用中正确显示。 ImageView什么都没显示。

我的代码是这样的:

  public void onPictureTaken(byte[] data, Camera camera) {
    try {
      File file = Utils.getOutputMediaFile(Utils.MediaFileType.Image);
      FileOutputStream os = new FileOutputStream(file);
      os.write(data);
      os.flush();
      os.close();

      final Uri uri = Uri.fromFile(file);
      showImage(uri);
    } catch (FileNotFoundException e) {
      Log.d(TAG, "onPictureTaken, e=" + e);
    } catch (IOException e) {
      Log.d(TAG, "onPictureTaken, e=" + e);
    }

    camera.startPreview();
  }

  private void showImage(Uri imageFileUri) {
    int w = mContentContainer.getWidth();
    int h = mContentContainer.getHeight();
    Bitmap bmp = Utils.loadBitmapFromFile(imageFileUri.getPath(), w, h);
    mImageView.setImageBitmap(bmp);
    mStatusTextView.setText("take photo: succcess");
  }

  public static Bitmap loadBitmapFromFile(String filename, int maxWidth, int maxHeight) {
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inJustDecodeBounds = true;

    BitmapFactory.decodeFile(filename, opt);
    Log.d(TAG, "loadBitmapFromFile, w=" + opt.outWidth + ", h=" + opt.outHeight);

    int widthRatio = (int) Math.ceil(opt.outWidth / maxWidth);
    int heightRatio = (int) Math.ceil(opt.outHeight / maxHeight);

    if (widthRatio > 1 || heightRatio > 1) {
      if (widthRatio > heightRatio) {
        opt.inSampleSize = widthRatio;
      } else {
        opt.inSampleSize = heightRatio;
      }
    }

    opt.inJustDecodeBounds = false;
    Bitmap bmp = BitmapFactory.decodeFile(filename, opt);
    Log.d(TAG, "loadBitmapFromFile, bmp=" + bmp);
    return bmp;
  }

从日志中,我看到宽度和高度是从文件中正确加载的,而bmp不是null,但ImageView只是空的。

奇怪的是,如果我的应用程序首先拍摄照片并使用showImage()显示照片(ImageView正确显示照片),那么之后,使用SurfaceView手机并使用showImage()进行显示,照片显示正确。但如果直接使用SurfaceView和showImage()手机,则ImageView为空。

有关ImageView为何空的任何评论?感谢。

1 个答案:

答案 0 :(得分:0)

尝试(参见comments):

  private void showImage(Uri imageFileUri) {
    int w = mContentContainer.getWidth();
    int h = mContentContainer.getHeight();
    Bitmap bmp = Utils.loadBitmapFromFile(imageFileUri.getPath(), w, h);
    mImageView.requestLayout(); //try to request the layout first
    mImageView.setImageBitmap(bmp);
    //if its still not working try to call invalidate() method here
    mStatusTextView.setText("take photo: succcess");
  }
相关问题