Click here to Skip to main content
15,889,335 members
Articles / Mobile Apps / Android
Tip/Trick

Bitmap combination

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
27 Aug 2013CPOL 11.6K   214   10  
Create a new bitmap by combining many bitmaps.

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:

Java
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.

Java
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)
Java
Canvas canvas = new Canvas(leftRight);

Image 1

Java
canvas.drawBitmap(left, 0, 0, new Paint());  

Image 2

Java
canvas.drawBitmap(right, left.getWidth(), 0, new Paint()); 

Image 3

And this is the result in device.

Image 4

With above explanation, I think you can create bitmap by combine many bitmaps vertically as below.

Java
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);
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Vietnam Vietnam
I'm Java developer.
I started Java web coding from 2007 to 2010. After that, I began to develop Android from 2010 to now.
In my thinking, sharing and connecting is the best way to develop.
I would like to study more via yours comments and would like to have relationship with more developers in the world.

Comments and Discussions

 
-- There are no messages in this forum --