Introduction
Sometimes we must create a new bitmap by combining many bitmaps. This article will explain about the ways to do
that using Canvas.
Using the code
Suppose that we have two bitmaps left, right, and left is bigger than right. To create new bitmap which is combined left and right horizontally,
code will as below:
private void horizontalCombine() {
int width = left.getWidth() + right.getWidth();
int height = Math.max(left.getHeight(), right.getHeight());
Bitmap leftRight = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(leftRight);
canvas.drawBitmap(left, 0, 0, new Paint());
canvas.drawBitmap(right, left.getWidth(), 0, new Paint());
imageView.setImageBitmap(leftRight);
}
I will explain more about code above.
int width = left.getWidth() + right.getWidth();
int height = Math.max(left.getHeight(), right.getHeight());
Bitmap leftRight = Bitmap.createBitmap(width, height, Config.ARGB_8888);
This will create new empty bitmap leftRight
which has:
- width = left.getWidth() + right.getWidth()
- height = left.getHeight()(because left bitmap is taller than)
Canvas canvas = new Canvas(leftRight);
canvas.drawBitmap(left, 0, 0, new Paint());
canvas.drawBitmap(right, left.getWidth(), 0, new Paint());
And this is the result in device.
With above explanation, I think you can create bitmap by combine many bitmaps vertically as below.
private void verticalCombine() {
int width = Math.max(left.getWidth(), right.getWidth());
int height = left.getHeight() + right.getHeight();
Bitmap leftRight = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(leftRight);
canvas.drawBitmap(left, 0, 0, new Paint());
canvas.drawBitmap(right, 0, left.getHeight(), new Paint());
imageView.setImageBitmap(leftRight);
}