Search code examples
androidperformancebitmapandroid-canvasbitmapfactory

A bitmap from many of them


Guys I have a solution to crate a bitmap from 5 different another ones. However, I want this solution to be faster. I could not find another easy and fast way to do same.

private void createImage() {
    // Magic numbers from image files
    int numberOfImages = 5;
    int imgWidth = 125;
    int imgHeight = 300;
    int totalwidth = imgWidth * numberOfImages;
    int totalheight = imgHeight;


    img = Bitmap.createBitmap(totalwidth, totalheight, Bitmap.Config.ARGB_8888);

    for (int i = 0; i < numberOfImages; i++) {
        Bitmap imgFile = BitmapFactory.decodeResource(context.getResources(), context.getResources().getIdentifier(
                "f" + i, "drawable", context.getPackageName()));
        for (int x = 0; x < imgWidth; x++) {
            for (int y = 0; y < imgHeight; y++) {
                int targetX = x + (i * imgWidth);
                int targetY = y;
                int color = imgFile.getPixel(x, targetY);
                img.setPixel(targetX, targetY, color);
            }
        }
    }


    img = Bitmap.createScaledBitmap(img, screenWidth, screenHeight, true);

}

Solution

  • You are mostly there. You've created a bitmap that is wide enough for them all.

    What you then need to do is draw the bitmaps directly onto it one at a time, but the whole bitmap at once, not pixel by pixel.

    You can do this using something call Canvas. Which aids in drawing things onto bitmaps.

    img = Bitmap.createBitmap(totalwidth, totalheight, Bitmap.Config.ARGB_8888);
    Canvas drawCanvas = new Canvas(img);
    
    for (int i = 0; i < numberOfImages; i++) {
        Bitmap imgFile = BitmapFactory.decodeResource(context.getResources(), context.getResources().getIdentifier(
                "f" + i, "drawable", context.getPackageName()));
    
              // Draw bitmap onto combo bitmap, at offset x, y.
              drawCanvas.drawBitmap(imgFile, i * imgWidth, 0, null);
    
    
    }