Reputation: 3541
I have a set of Bitmaps
and I want to merge them into a single Bitmap
so that they are all visible in a vertical format.
Ideally, it would look something like:
|Image1|
|Image2|
|Image3|
| . | <--- a single Bitmap
| . |
| . |
I saw a question which suggested using a Canvas
to draw the Bitmaps
over each other, but I can't figure out how I can format it for my problem.
My Bitmaps
are generated in a loop as follows:
for (int i = 0; i < bitmapSet.size(); i++) {
Bitmap bitmap = bitmapSet.get(i);
// Merging them together would go here
}
Upvotes: 1
Views: 1190
Reputation: 49817
If you want to display multiple images on top of each other the easiest solution is to use a LayerDrawable
. You can create a LayerDrawable
either in code or in xml.
LayerDrawable
in codeIf you want to stack dynamic images you have to create the LayerDrawable
in code. You can do that like this:
final LayerDrawable layerDrawable = new LayerDrawable(new Drawable[]{
someDrawable,
anotherDrawable,
aThirdDrawable
});
The Drawables
will be drawn in the same order as the occur in the array. After creating the LayerDrawable
you can use it like any other Drawable
and the LayerDrawable
will take care of the rest.
LayerDrawable
in XMLIf you want to stack a few assets contained in your resources folder on top of each other you just have to create a new xml file with an appropriate name in your res/drawable folder. Defining the LayerDrawable
works like this:
<?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>
For each Drawable
you want to stack you just need to add another <item />
tag with the reference to the Drawable
. Again the order of the items in the <layer-list />
tag determines the draw order.
In your specific case since you seem to have a List
of Bitmaps
you could create a LayerDrawable
like this:
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);
But of course it would be much better if you would work only with Drawables
from the start in which case the code could be simplified to this:
final List<Drawable> images = ...;
final LayerDrawable layerDrawable = new LayerDrawable(images.toArray(new Drawable[images.size()]));
You can find more information about the LayerDrawable
in the official documentation!
Upvotes: 3