首页 > 解决方案 > 看来 ImageView.setImageBitmap 不起作用

问题描述

我有一个活动,您可以在其中绘制位图,并使用意图将其发送到下一个活动并将其放入其中的 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);

我究竟做错了什么?

标签: javaandroidbitmap

解决方案


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

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);

这是的来源setImageBitmap()

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

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


推荐阅读