绘制相同大小的方形瓷砖以适合屏幕

时间:2015-07-27 19:27:47

标签: android canvas 2d

我有一个自定义视图,可以绘制一个n * m大小的矩阵。

我想计算每个图块的大小,以便所有图块都适合屏幕。

目前,我正在通过在已加载的drawable上调用getIntrinsicWidth()来计算切片大小。

瓷砖的绘制正在onDraw回调中完成:

@Override
protected void onDraw(Canvas canvas) {
    int a_wid = arenaMap.getMapWidth(); 
    int a_height = arenaMap.getMapHeight();
    Drawable tile;

    for (int x = 0; x < a_wid; x++) {
        for (int y = 0; y < a_height; y++) {
            int ix;
            int iy;
            if (tall) {
                ix = (arena_x_lower_bound + arenaMap.getMapHeight()) y;
                iy = arena_y_lower_bound + x;
            } else {
                ix = x + arena_x_lower_bound;
                iy = y + arena_y_lower_bound;
            }
            tile = tileForLocation(x, y);
            tile.setBounds(ix * TILE_SIZE, iy * TILE_SIZE, ix * TILE_SIZE + TILE_SIZE, iy * TILE_SIZE + TILE_SIZE);
            tile.draw(canvas);
        }
    }
}

onSizeChanged()内,我定义了下限/上限:

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    int tiles_wide = w / TILE_SIZE;
    int tiles_high = h / TILE_SIZE;
    tall = tiles_high > tiles_wide;
    int side_border_height;
    int side_border_width;
    if (tall) {
        side_border_width = (tiles_wide - arenaMap.getMapHeight()) / 2;
        side_border_height = (tiles_high - arenaMap.getMapWidth()) / 2;
        arena_x_lower_bound = side_border_width;
        arena_y_lower_bound = side_border_height;
    } else {
        side_border_width = (tiles_wide - arenaMap.getMapWidth()) / 2;
        side_border_height = (tiles_high - arenaMap.getMapHeight()) / 2;
        arena_x_lower_bound = side_border_width;
        arena_y_lower_bound = side_border_height;
    }
}

0 个答案:

没有答案