How to draw multiple bitmaps vertically, one below the other

I'm trying to draw a bunch of bitmaps vertically one below the other like this :

Original Bitmap :

enter image description here

Result expected :

enter image description here

Code :

   int repeater = 4;
   Bitmap bitmapTextSticker = ImageUtils.drawable2Bitmap(ResourceUtils.getDrawable(R.drawable.icon));
   Bitmap background = Bitmap.createBitmap(bitmapTextSticker.getWidth(), bitmapTextSticker.getHeight() * repeater, Bitmap.Config.ARGB_8888);
   Canvas canvas = new Canvas(background);
   int top = 0;
   for (int i = 0; i < repeater; i++) {
          top = (i == 0 ? 0 : top + bitmapTextSticker.getHeight());
                canvas.drawBitmap(bitmapTextSticker, 0f, top, null);
     }

The above code is working, but the output is cropped.

enter image description here

Upvotes: 0

Views: 95

Answers (2)

user496854
user496854

Reputation: 6810

I'm not sure if I'm missing something in your question, but all you have to do is change the top coordinate for each bitmap when calling drawBitmap(). In your specific code, just add:

top += height;

inside the for loop

Edit: from your updated question, it sounds like a Bitmap scaling issue, not a problem with position. Even your 1st bitmap is cropped. So, you should probably use a different canvas.drawbitmap() method:

public void drawBitmap (Bitmap bitmap, Rect src,  RectF dst, Paint paint)

You can specify the dimensions of the destination Rect, which should let it scale properly. So, your code should be:

for(...){
   ...
   RectF dest = new RectF(new Rect(0, top, bitmapTextSticker.getWidth(), bitmapTextSticker.getHeight()));
   canvas.drawBitmap(bitmapTextSticker, null, dest, null);
}

Upvotes: 1

The issue was I didn't set the density for the bitmap and the canvas :

  ArrayList<Bitmap> bitmaps = new ArrayList<>();
        for (int i = 0; i < repeater; i++) bitmaps.add(bmp);
        int height = 0;
        for (Bitmap map : bitmaps) height += map.getHeight();

        Bitmap bitmap = Bitmap.createBitmap(bmp.getWidth(), height, Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(bitmap);
        canvas.setDensity(DisplayMetrics.DENSITY_MEDIUM);
        bitmap.setDensity(DisplayMetrics.DENSITY_MEDIUM);
        int drawHeight = 0;
        for (Bitmap map : bitmaps) {
            if (map != null) {
                canvas.drawBitmap(map, 0, drawHeight, null);
                drawHeight += map.getHeight();
            }
        }
        return bitmap;

Upvotes: 0

Related Questions