我有一组位图
,我想将它们合并为一个位图
,以便它们都以垂直格式可见。
理想情况下,它看起来像:
|Image1|
|Image2|
|Image3|
| . | <--- a single Bitmap
| . |
| . |
我看到一个问题,建议使用 Canvas
相互绘制 Bitmap
,但我不知道如何针对我的问题对其进行格式化。
我的位图
是在循环中生成的,如下所示:
for (int i = 0; i < bitmapSet.size(); i++) {
Bitmap bitmap = bitmapSet.get(i);
// Merging them together would go here
}
最佳答案
如果您想在彼此之上显示多个图像,最简单的解决方案是使用 LayerDrawable
。您可以创建LayerDrawable
无论是在代码中还是在 xml 中。
1) 创建 LayerDrawable
在代码中
如果你想堆叠动态图像,你必须创建LayerDrawable
在代码中。你可以这样做:
final LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{
someDrawable,
anotherDrawable,
aThirdDrawable
});
Drawables
将按照与数组中出现的顺序相同的顺序进行绘制。创建LayerDrawable
后您可以像其他任何一样使用它 Drawable
和 LayerDrawable
会处理剩下的事情。
2) 创建 LayerDrawable
在 XML 中
如果您想将资源文件夹中包含的一些资源堆叠在一起,您只需在 res/drawable 文件夹中创建一个具有适当名称的新 xml 文件。定义LayerDrawable
工作原理如下:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/someDrawable"/>
<item android:drawable="@drawable/anotherDrawable"/>
<item android:drawable="@drawable/aThirdDrawableJustForGoodMeasure"/>
</layer-list>
对于每个 Drawable
你想堆叠你只需要添加另一个 <item />
标签引用 Drawable
。再次说明 <layer-list />
中项目的顺序标签决定绘制顺序。
在您的具体情况下,因为您似乎有 List
的Bitmaps
你可以创建一个LayerDrawable
像这样:
final List<Bitmap> images = ...;
final Drawable[] layers = new Drawable[images.size()];
for (int i = 0, count = images.size(); i < count; i++) {
layers[i] = new BitmapDrawable(getResources(), images.get(i));
}
final LayerDrawable layerDrawable = new LayerDrawable(layers);
但是,如果您只使用Drawables
,当然会更好。从一开始,在这种情况下,代码可以简化为:
final List<Drawable> images = ...;
final LayerDrawable layerDrawable = new LayerDrawable(images.toArray(new Drawable[images.size()]));
您可以找到有关 LayerDrawable
的更多信息在 official documentation !
关于java - Android 将一组位图合并为一个位图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33471302/