Android开发:将小磁贴/位图组合成一个位图

时间:2011-07-14 15:23:13

标签: android 2d surfaceview android-canvas map-edit

我试图将我的所有小图像,如草,水和沥青等等,放到一个位图中。

我有一个像这样的数组:

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

基本上这是10 * 10 每个数字都是图像(数字).png

的占位符

但我如何将它们合并在一起?

//西蒙

2 个答案:

答案 0 :(得分:6)

好的,所以下面的代码片段应该并排组合两个图像。我不想推断10,但我相信你会自己弄清楚for循环。

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

答案 1 :(得分:0)

如果所有图块的大小相同,您可以创建一个大的Bitmap并在正确的位置绘制所有图块。例如:

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