【问题标题】:It seems that ImageView.setImageBitmap doesn't work看来 ImageView.setImageBitmap 不起作用
【发布时间】:2019-02-16 07:08:50
【问题描述】:

我有一个活动,您可以在其中绘制位图,并使用意图将其发送到下一个活动并将其放入其中的 ImageView 中。由于某种原因,它不会产生错误,但也不会将图像设置为应有的样子。 当宽度和高度不兼容时,这会是一个问题吗?

ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Intent i = new Intent(getApplicationContext(), PrintActivity.class);
i.putExtra("bitmap", byteArray);
startActivity(i);

我只想提一下,这种方法在其他活动中也适用,因为我多次跨活动发送位图。

获取意图的活动:

img = findViewById(R.id.img);

byte[] byteArray = getIntent().getByteArrayExtra("bitmap");
if (byteArray.length > 0) {
    Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
    ImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); // In a different thread this seemed to help the OP but it didn't in my case
    img.setImageBitmap(bmp);

我也尝试将位图保存到画廊,但它给出了多个错误,一些表明位图为空。虽然我不明白这是怎么回事,因为它是画布的位图。我用这个来获取它:

public Bitmap getBitmap() {
    return mBitmap;
}

而mbitmap就是用来写在画布上的:

canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

我做错了什么?

【问题讨论】:

    标签: java android bitmap


    【解决方案1】:

    我看到您通过压缩为字节数组来移动位图,然后再次对其进行解码。请注意,BitMaps 实现了Parcelable,这很好,因为您可以将 Parcelables 直接放入 Intent 中

    Intent intentions = new Intent(this, someActivity.class);
    intentions.putExtra("parcelable_photo", mPhoto);
    

    获取包裹

    Intent received = getIntent();
    Bitmap mPhoto = (Bitmap) received.getExtras().getParcelable("parcelable_photo");
    

    这应该比您当前的方法更快,打字工作更少。

    要在图像视图中设置此位图,以下应该可以解决问题:

    ImageView mImg = findViewById(R.id.img_id);
    img.setImageBitmap(mPhoto);
    

    这是sourcesetImageBitmap()

    我不知道ImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null),但我希望上述方法可以解决问题。

    如果问题仍然存在,请随时发表评论

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-30
      相关资源
      最近更新 更多