我正在使用 LayerDrawable 来合并多个 Drawable。现在,我想将我的 LayerDrawable 导出到一个文件中。
我试过这样:
Bitmap b = ((BitmapDrawable)myLayerDrawable).getBitmap();
--> ClassCastException...
我能做些什么?
您是否尝试过将 Drawable 绘制到位图画布上?我认为调用顺序将类似于:
Bitmap b = Bitmap.createBitmap(int width, int height, Bitmap.Config config);
myLayerDrawable.draw(new Canvas(b));
然后您可以将 Bitmap 对象写入输出流。
感谢两位用户在我之前回答(@Kyle P和@Anjum Shrimali)。受到他们的回答的启发......这对我的情况很好:
final int width = myLayerDrawable.getIntrinsicWidth();
final int height = myLayerDrawable.getIntrinsicHeight();
final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
myLayerDrawable.setBounds(0, 0, width, height);
myLayerDrawable.draw(new Canvas(bitmap));
谢谢您的帮助。但是像我这样的初学者需要一些更具体的代码。我尝试了以下方法,它对我有用。
Bitmap b = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
layerDrawable.setBounds(0, 0, getWidth(), getHeight());
layerDrawable.draw(new Canvas(b));
最终,b(位图)是所需的组合位图。
如果有人想要@Mir-Ismaili答案的 kotlin 版本
val height = layerDrawable.intrinsicHeight
val width = layerDrawable.intrinsicWidth
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
layerDrawable.setBounds(0, 0, width, height)
layerDrawable.draw(Canvas(bitmap))