LoginSignup
2
2

More than 5 years have passed since last update.

Canvas を使ってタイル画像を敷き詰める

Posted at

概要

コード上で Canvas を使ってタイル画像を敷き詰める方法。
Surface ビューに drawable に保存してある背景タイルを敷き詰めたいときに、 xml からだとうまく動作しなかったため、この方法で描画した。

コード上で drawable のビットマップを取得するのには BitmapFactory.decodeResource を使用した。

コード

    /**
     * タイル画像をキャンバス上に敷き詰める.
     * @param canvas 描画用キャンバス.
     * @param resource リソースオブジェクト.
     * @param resourceId タイル画像のリソースID.
     */
    public static void fillByTile(@NonNull Canvas canvas,
                                  @NonNull Resources resource,
                                  @DrawableRes int resourceId)
    {
        int canvasWidth = canvas.getWidth();
        int canvasHeight = canvas.getHeight();

        Bitmap tile = BitmapFactory.decodeResource(resource, resourceId);
        int tileWidth = tile.getWidth();
        int tileHeight = tile.getHeight();

        for (int y = 0; y < canvasHeight; y += tileHeight)
        {
            for (int x = 0; x < canvasWidth; x += tileWidth)
            {
                canvas.drawBitmap(tile, x, y, null);
            }
        }
    }
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2