Search code examples
javaandroidandroid-canvasandroid-imageandroid-bitmap

What is the correct way to horizontally add some spaced image into a Canvas?


I am absolutly new in Android development and I have the followind doubt.

I have to draw images one next to each other into a Canvas object.

So let to an example: I have this icon (it is pretty huge and I have to resize it):

enter image description here

So I have to put 3 of these icon one next to each other (adding some white space between an image and the next one).

So I have done something like this:

// Load the 2 images for the creation of the "difficulty graphic":
Bitmap chefHatOk = BitmapFactory.decodeResource(getResources(), R.drawable.chef_hat_ok);

// Where the previus image will be drawn:
Canvas canvas = new Canvas();

So I think that I can add the previous image to the Canvas doing something like this:

canvas.drawBitmap(smallImage, 0f, 0f, null); 

I think that the first 0f value represent the horizontal space before the inserted image (the offset), correct me if I am doing wrong assertion.

So, how can I add 3 of these images one next to each other leaving some white space between an image and the next one?


Solution

  • Something like this should work:

    Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);
    
    int space = 10; // the space between images
    
    for(int i = 0; i < 3; i++) {
        canvas.drawBitmap(smallImage, i * (smallImage.getWidth() + space), 0, null);
    }
    
    // do whatever you want with output