Android Development: Combining small tiles/bitmaps

2019-02-26 00:12发布

问题:

Im trying to get all my small images like grass, water and asphalt and so on, into one bitmap.

I have an Array that goes like this:

public int Array[]={3, 1, 3, 3, 1, 1, 3, 3, 3, 3, 
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
            1, 1, 1, 1 ,1 ,1, 1, 1 ,1 ,1 
            ,7 ,7 ,7, 7, 7 ,7, 7 ,7 ,7, 7 
            ,7 ,7 ,7 ,7, 7 ,7, 7 ,7 ,7 ,7 
            ,7 ,7 ,7 ,7, 7, 7, 7, 7 ,7 ,7 
            ,7 ,7 ,7 ,7, 7, 7 ,7 ,7 ,7 ,7 
            ,7 ,7 ,7 ,7, 7, 7, 7 ,7 ,7, 7 
            ,6, 6, 6, 6, 6 ,6 ,6, 6, 6 ,6 
            ,6, 6, 6 ,6, 6, 6 ,6, 6 ,6 ,6 };

So basicly this is a 10*10 Every number is a placeholder for a image(number).png

But how do i merge them together?

//Simon

回答1:

Okay so the following snippet should combine two images side by side. I didn't want to extrapolate for 10, but I'm sure you'll figure out the for loops by yourself.

public Bitmap combineImages(Bitmap c, Bitmap s) {
    Bitmap cs = null; 

    int width, height = 0; 

    if(c.getWidth() > s.getWidth()) { 
      width = c.getWidth() + s.getWidth(; 
      height = c.getHeight()); 
    } else { 
      width = s.getWidth() + s.getWidth(); 
      height = c.getHeight(); 
    } 

    cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 

    Canvas comboImage = new Canvas(cs); 

    comboImage.drawBitmap(c, 0f, 0f, null); 
    comboImage.drawBitmap(s, c.getWidth(), 0f, null); 
    //notice that drawing in the canvas will automagically draw to the bitmap
    //as well
    return cs; 
  } 


回答2:

If all the tiles are the same size you can create one large Bitmap and draw all the tiles in the right location. For example:

private static final int MAP_WIDTH = 10; // in tiles
private static final int MAP_HEIGHT = 10;
private static final int TILE_WIDTH = 10;
private static final int TILE_HEIGHT = 10;

public Bitmap createMap() {
    Bitmap mainBitmap = Bitmap.createBitmap(TILE_WIDTH * MAP_WIDTH, TILE_HEIGHT * MAP_HEIGHT,
            Bitmap.Config.ARGB_8888);
    Canvas mainCanvas = new Canvas(mainBitmap);
    Paint tilePaint = new Paint();
    for (int i = 0; i < map.length; i++) {
        // Grab tile image (however you want - don't need to follow this)
        Bitmap tile = BitmapFactory.decodeResource(getResources(), getResources()
                .getIdentifier(String.valueOf(map[i]), "drawable", "your.package"));

        // Draw tile to correct location
        mainCanvas.drawBitmap(tile, (i % MAP_WIDTH) * TILE_WIDTH,
                (i / MAP_WIDTH) * TILE_HEIGHT, tilePaint);
    }
    return mainBitmap;
}