安卓平铺位图

46

我想在Android中加载一张位图并将其平铺。目前我正在我的视图中使用以下代码来显示一个位图:

canvas.drawBitmap(bitmap, srcRect, destRect, null)

我想在我的应用程序中将这个位图作为背景图片使用,并希望在X和Y方向上重复位图。

我已经看到了BitmapShader类的TileMode.REPEAT常量,但不确定是否应该用于重复实际位图或用于对位图应用滤镜。


有人知道如何在Java代码中实现此功能而不使用XML吗? - endryha
8个回答

132

你需要在XML文件中完成这个操作,而不是在Java代码中。我自己没有尝试过,但我找到了这个示例。

<xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/MainLayout"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:background="@drawable/backrepeat"
>

然后在名为backrepeat.xml的xml中

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/back" 
    android:tileMode="repeat" />

参考


4
仅补充一点,backrepeat.xml应放置在“drawable”文件夹中。 - Ben Gotow
可能有点过于追求细节,但第一行应该写成 - <?xml version="1.0" encoding="utf-8"?> - Neil
1
这在最近的Android API版本(大约4.x左右)中有效,但至少在API 2.2之前不起作用。有人知道解决方法/修复方法以及更多细节吗?http://developer.android.com/reference/android/R.attr.html#tileMode参考资料说它是自API 1以来添加的,但仍然不起作用。 - Jonny
1
这个例子无处不在,但为什么我们假设它有效,而实际上它会在每个图像周围创建最丑陋的空白填充瓷砖背景?它几乎没有用。我尝试了所有可能的方法,包括使用透明度和不透明度。 - Herb Meehan

38

找到了代码的版本:

  BitmapDrawable TileMe = new BitmapDrawable(MyBitmap);
  TileMe.setTileModeX(Shader.TileMode.REPEAT);
  TileMe.setTileModeY(Shader.TileMode.REPEAT);

  ImageView Item = new ImageView(this);
  Item.setBackgroundDrawable(TileMe);

如果您有一个可平铺的drawable,那么可以使用它来创建BitmapDrawable:

  BitmapDrawable TileMe = new BitmapDrawable(BitmapFactory.decodeResource(getResources(), R.drawable.tile));

这很好用,但是你怎么只在垂直方向上重复它呢?我尝试移除setTileModeX,但那样它根本就不起作用了。 - William L.
@WilliamL。奇怪。文档似乎说它应该只使用其中一个。最好的猜测是尝试使用Shader.TileMode.CLAMP,然后看看会发生什么。 - Izkata
仅在水平方向重复时它有效,但仅在垂直方向上不起作用。而 CLAMP 的作用与一开始未设置平铺模式相同。 - William L.

16

上面的backrepeat.xml有缺陷

<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/tile"
    android:tileMode="repeat"
    android:dither="true" />

21
为什么会出现 Bug,这个修复方法是如何解决它的? - Alex Spurling
这个添加了:android:dither="true",如果平铺本来就不好用,则不起作用。 - Herb Meehan

6

看起来有些人对在View的onDraw方法中实现此功能感兴趣。以下代码适用于我:

bgTile = BitmapFactory.decodeResource(context.getResources(), R.drawable.bg_tile);

float left = 0, top = 0;
float bgTileWidth = bgTile.getWidth();
float bgTileHeight = bgTile.getHeight();

while (left < screenWidth) {
    while (top < screenHeight) {
        canvas.drawBitmap(bgTile, left, top, null);
        top += bgTileHeight;
    }
    left += bgTileWidth;
    top = 0;
}

它将填满整个区域。最后一个瓷砖可能不完整,屏幕的右/下方最大空间仍将被绘制。 - kgiannakakis
我只是在我的画布上使用了这个段落,而不是全部,因此显然你会得到额外的绘制,因为宽度和高度不能被图像大小整除。我删掉了我的评论,因为它与问题无关。抱歉! - stealthcopter
在这种情况下,您会使用BitmapDrawable.setBounds和BitmapDrawable.draw(Canvas)。 - tactoth

5
<xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/MainLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/back"
    android:tileMode="repeat"
>

这对我来说很有效。我不需要单独创建位图。我在布局中使用了tileMode属性。


谢谢,我发现这是最简单的方法。 - patrick-fitzgerald

1
只需在onCreate()方法中添加以下代码即可:-
 final Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.drawable.actionbar_bg);
 final BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
 bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
 final ActionBar bar = getSupportActionBar();
 bar.setBackgroundDrawable(bitmapDrawable);

0
如果您想要仅在垂直方向上重复背景,则可以将布局的宽度设置为“wrap_content”,而如果您想要将背景设置为水平重复,则将高度设置为“wrap_content”。如果高度和宽度都设置为“fill_parent”,则它将在X和Y方向上平铺。
例如,以下代码将在垂直方向上重复您的背景:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:background="@drawable/news_detail_activity_bg">
</LinearLayout>

0
/* Tiled Layer Bitmap*/


public class TiledLayer {
private int cellWidth;
private int cellHeight;
private int yPosition = 0, xPosition = 0;
private int[][] grid;
private Image image;
private int[] tileXPositions;
private int[] tileYPositions;
private ArrayList animatedTiles;
private int numberOfTiles;
private int numberOfColumns;
private int numberOfRows;
private int gridColumns;
private int gridRows, width, height;

public TiledLayer(Image image, int columns, int rows, int tileWidth,
        int tileHeight, int width, int height) {
    this.grid = new int[columns][rows];
    this.gridColumns = columns;
    this.gridRows = rows;
    this.width = columns * tileWidth;
    this.height = rows * tileHeight;
    this.animatedTiles = new ArrayList();
    setStaticTileSet(image, tileWidth, tileHeight);
}

public void setStaticTileSet(Image image, int tileWidth, int tileHeight) {
    this.image = image;
    this.cellWidth = tileWidth;
    this.cellHeight = tileHeight;
    int columns = 64;//image.getWidth() / tileWidth;
    int rows =40;// image.getHeight() / tileHeight;
    this.tileXPositions = new int[columns];
    int pos = 0;
    for (int i = 0; i < columns; i++) {
        this.tileXPositions[i] = pos;
        pos += tileWidth;
    }
    this.tileYPositions = new int[rows];
    pos = 0;
    for (int i = 0; i < rows; i++) {
        this.tileYPositions[i] = pos;
        pos += tileHeight;
    }

    if (columns * rows < this.numberOfTiles) {
        // clear the grid, when there are not as many tiles as in the
        // previous set:
        for (int i = 0; i < this.grid.length; i++) {
            for (int j = 0; j < this.grid[i].length; j++) {
                this.grid[i][j] = 0;
            }
        }
    }
    this.numberOfTiles = columns * rows;
    this.numberOfColumns = columns;
    this.numberOfRows = rows;
}

public int createAnimatedTile(int staticTileIndex) {
    if (staticTileIndex >= this.numberOfTiles) {

        throw new IllegalArgumentException("invalid static tile index: "
                + staticTileIndex + " (there are only ["
                + this.numberOfTiles + "] tiles available.");

    }
    this.animatedTiles.add(new Integer(staticTileIndex));
    return -1 * (this.animatedTiles.size() - 1);
}

public void setAnimatedTile(int animatedTileIndex, int staticTileIndex) {
    if (staticTileIndex >= this.numberOfTiles) {

    }
    int animatedIndex = (-1 * animatedTileIndex) - 1;
    this.animatedTiles.set(animatedIndex, new Integer(staticTileIndex));
 }

 public int getAnimatedTile(int animatedTileIndex) {
    int animatedIndex = (-1 * animatedTileIndex) - 1;
    Integer animatedTile = (Integer) this.animatedTiles.get(animatedIndex);
    return animatedTile.intValue();
 }
 public void setCell(int col, int row, int tileIndex) {
    if (tileIndex >= this.numberOfTiles) {

        throw new IllegalArgumentException("invalid static tile index: "
                + tileIndex + " (there are only [" + this.numberOfTiles
                + "] tiles available.");

    }
    this.grid[col][row] = tileIndex;
}

 public int getCell(int col, int row) {
    return this.grid[col][row];
 }

 public void fillCells(int col, int row, int numCols, int numRows,
        int tileIndex) {
    if (tileIndex >= this.numberOfTiles) {

        throw new IllegalArgumentException("invalid static tile index: "
                + tileIndex + " (there are only [" + this.numberOfTiles
                + "] tiles available.");

    }
    int endCols = col + numCols;
    int endRows = row + numRows;
    for (int i = col; i < endCols; i++) {
        for (int j = row; j < endRows; j++) {
            this.grid[i][j] = tileIndex;
        }
    }
 }

    public final int getCellWidth() {
    return this.cellWidth;
 }

    public final int getCellHeight() {
    return this.cellHeight;
 }

 public final int getColumns() {
    return this.gridColumns;
 }

public final int getRows() {
    return this.gridRows;
}

public final void paint(Graphics g) {
    int clipX = 0;// g.getClipX();
    int clipY = 0;// g.getClipY();
    int clipWidth = width;// g.getClipWidth();
    int clipHeight = height;// g.getClipHeight();

    // jmt restore clip to previous state

    int x = this.xPosition;
    int y = this.yPosition;
    int[][] gridTable = this.grid;
    for (int i = 0; i < this.gridColumns; i++) {
        int[] gridRow = gridTable[i];
        for (int j = 0; j < gridRow.length; j++) {
            int cellIndex = gridRow[j];
            if (cellIndex != 0) {
                // okay this cell needs to be rendered:
                int tileIndex;
                if (cellIndex < 0) {
                    Integer tile = (Integer) this.animatedTiles
                            .get((-1 * cellIndex) - 1);
                    tileIndex = tile.intValue() - 1;
                } else {
                    tileIndex = cellIndex - 1;
                }
                // now draw the tile:
                g.save(Canvas.CLIP_SAVE_FLAG);
                // jmt: clear the screen
                Rect r = new Rect(0, 0, cellWidth, cellHeight);
                g.clipRect(r);
                g.setClip(x, y, this.cellWidth, this.cellHeight);
                int column = tileIndex % this.numberOfColumns;
                int row = tileIndex / this.numberOfColumns;
                int tileX = x - this.tileXPositions[column];
                int tileY = y - this.tileYPositions[row];

                g.drawImage(this.image, tileX, tileY);
                g.restore();
            }
            y += this.cellHeight;
        } // for each row
        y = this.yPosition;
        x += this.cellWidth;
    } // for each column

        // reset original clip:
        g.setClip(clipX, clipY, clipWidth, clipHeight);
     }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接