【问题标题】:Android Bitmap is blackAndroid位图是黑色的
【发布时间】:2010-10-12 16:05:33
【问题描述】:

我正在尝试将文本文件中的地图绘制到位图上,但位图全黑

首先我加载一个看起来像这样(缩短)的文本文件:

0000000000(200 宽)
0111111110
0111100010
0000111110
0000111000
0000000000
(120高度)

其中“1”是地面,“0”是墙壁,1 应该是白色,0 应该是黑色。

代码:

public Map(String map) {
    this.map = map;
    init();
}

public void init() {
    mapArray = new int[WIDTH*HEIGHT];
    String[] splitMap = map.split("\n");
    int width = splitMap[0].length();
    int height = splitMap.length;
    int[] colors = new int[WIDTH * HEIGHT];
    for(int y = 0; y < height; y++) {
        for(int x = 0; x < width; x++) {
            int type = Integer.valueOf(splitMap[y].charAt(x));
            setType(x, y, type);
            if(type == WALL) {
                setColor(x, y, Color.rgb(0, 0, 0), colors);
            } else if(type == GROUND) {
                setColor(x, y, Color.rgb(255, 255, 255), colors);
            } else if(type == GOAL) {
                setColor(x, y, Color.rgb(255, 255, 255), colors);
            }
        }
    }
    bitmap = Bitmap.createBitmap(colors, WIDTH, HEIGHT, Config.ARGB_8888);
}

public void setColor(int x, int y, int color, int[] colors) {
    for(int y1 = 0; y1 < 4; y1++) {
        for(int x1 = 0; x1 < 4; x1++) {
            colors[(x + x1) + (y + y1) * WIDTH] = color;
        }
    }
}

public void setPixel(int x, int y, int color) {
    for(int y1 = 0; y1 < 4; y1++) {
        for(int x1 = 0; x1 < 4; x1++) {
            bitmap.setPixel(x + x1, y + y1, color);
        }
    }
}

public void setType(int x, int y, int type) {
    for(int y1 = 0; y1 < 4; y1++) {
        for(int x1 = 0; x1 < 4; x1++) {
            mapArray[(x + x1) + (y + y1) * WIDTH] = type;
        }
    }
}

public int getType(int x, int y) {
    return mapArray[x + y * WIDTH];
}

public void doDraw(Canvas canvas) {
    canvas.drawBitmap(bitmap, 0, 0, null);
}

private final static int WALL = 0;
private final static int GROUND = 1;
private final static int GOAL = 2;
private final static int WIDTH = 800;
private final static int HEIGHT = 480;
private int[] mapArray = null;
private String map = null;
public Bitmap bitmap;

【问题讨论】:

    标签: android bitmap


    【解决方案1】:
    int type = Integer.valueOf(splitMap[y].charAt(x));
    

    这就是导致问题的线路。

    scala> Integer.valueOf('1')             
    res3: java.lang.Integer = 49
    
    scala> Integer.valueOf('0')
    res4: java.lang.Integer = 48
    

    问题是 charAt 给你一个字符,然后你将它转换成一个整数。你真正想做的是Integer.parseInt(splitMap[y].substring(x,x+1)

    Integer.valueOf("0".substring(0,1))  
    res7: java.lang.Integer = 0
    

    这说明了一个教训——不要在没有提供默认值的情况下离开 switch 语句;同样,永远不要离开 if/else if/... 而不离开 else。即使您希望永远不会碰到它,如果这样做,您也应该输入一些明显的错误消息;它将帮助您调试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 2013-01-04
      • 2011-11-15
      • 1970-01-01
      • 2011-10-19
      • 2016-03-31
      • 1970-01-01
      相关资源
      最近更新 更多