如何绘制对象使用Parcelable将退还(How to Pass Drawable using P

2019-06-23 11:12发布

我有一个类在那里我有一个Drawable作为成员。
这个类我使用作为整个活动的发送数据Parcelable额外费用。

对于我已经扩展了parceble,并实现所需的功能。

我能够发送使用读/写INT /串的基本数据类型。
但我面临的问题,同时编组的可绘制对象。

对于我试图转换Drawablebyte array ,但我正在逐渐造型异常。

我使用下面的代码隐蔽我可绘制到字节数组:

Bitmap bitmap = (Bitmap)((BitmapDrawable) mMyDrawable).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[]byteArray = stream.toByteArray();
out.writeInt(byteArray.length);
out.writeByteArray(byteArray);

而转换的字节数组绘制我使用下面的代码:

final int contentBytesLen = in.readInt();
byte[] contentBytes = new byte[contentBytesLen];
in.readByteArray(contentBytes);
mMyDrawable = new BitmapDrawable(BitmapFactory.decodeByteArray(contentBytes, 0, contentBytes.length));

当我运行此我得到类转换异常。

我们怎么可以写/使用HashMap的传递绘制对象?
有没有什么办法,使我们可以在包裹通过绘制对象。

谢谢。

Answer 1:

正如你已经转换可绘制在你的代码为位图,为什么不使用位图作为Parcelable类的成员。

位图默认情况下,API实现Parcelable,通过使用位图,你不需要做任何事情在你的代码的特殊,它会被包裹自动处理。

或者,如果你坚持使用可绘制,实现您的Parcelable因为是这样的:

public void writeToParcel(Parcel out, int flags) {
  ... ...
  // Convert Drawable to Bitmap first:
  Bitmap bitmap = (Bitmap)((BitmapDrawable) mMyDrawable).getBitmap();
  // Serialize bitmap as Parcelable:
  out.writeParcelable(bitmap, flags);
  ... ...
}

private Guide(Parcel in) {
  ... ...
  // Deserialize Parcelable and cast to Bitmap first:
  Bitmap bitmap = (Bitmap)in.readParcelable(getClass().getClassLoader());
  // Convert Bitmap to Drawable:
  mMyDrawable = new BitmapDrawable(bitmap);
  ... ...
}

希望这可以帮助。



Answer 2:

在我的应用程序,我救了绘制对象/位图缓存,并可随时使用文件的路径字符串,而不是将其传递。

不是你正在寻找一个解决方案,但至少有一些替代你的问题。



文章来源: How to Pass Drawable using Parcelable