java - 看来 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);
我究竟做错了什么?
解决方案
我看到您通过压缩为字节数组来移动位图,然后再次解码它们。请注意,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)
,但我希望上述方法可以解决问题。
如果问题仍然存在,请随时发表评论
推荐阅读
- deployment - Gitlab CI/CD - 如何从一个分支部署多个环境?
- excel - VBA:如何通过名称调用用户窗体对象(循环)
- arcgis-runtime-net - ArcGIS 运行时 WPF 草图编辑器
- android - 不明白这在谷歌游戏商店电子邮件中意味着什么
- react-admin - React-admin ReferenceInput 拉取文档 id 而不是源字段
- javascript - 如何使用 d3js 从引导程序显示模式窗口?
- r - 如何通过组合行名和列名来重塑二维矩阵
- c - 在 C 中将 char 写入 struct
- azure - 从存储帐户创建 Azure Databricks 笔记本
- javascript - setActivity 和 setPresence 有什么区别?