0
0

More than 5 years have passed since last update.

uGUIで動的にサムネイルを生成する

Last updated at Posted at 2019-05-24

やりたいこと

  • ステージ一覧で、ステージマップのサムネイルを動的に生成して張りつけたい。
    • 一覧される各要素は、動的に生成され、レイアウトグループで配置されます。
  • uGUIで、動的にSpriteを生成してImageに貼り付けます。

やったこと

  • サムネイルの生成は時間がかかるので、非同期に行います。
  • 個々のサムネイルを自律的に生成させます。
private IEnumerator MakeThumbnail () {
    this.Loading.SetActive (true); // クルクルを表示
    this.Thumbnail.gameObject.SetActive (false); // サムネを非表示
    yield return null;
    var size = Mathf.Max (this.Level.Width, this.Level.Height); // 縦横大きい方
    var dx = (size - this.Level.Width) / 2; // 中央寄せのため横のパディング
    var dy = (size - this.Level.Height) / 2; // 中央寄せのため縦のパディング
    this.Texture2D = new Texture2D (size, size); // テクスチャを生成
    for (var y = 0; y < size; y++) {
        for (var x = 0; x < size; x++) {
            var color = this.Level.Matrix [x - dx, y - dy].Color; // 色を取得 (範囲外は自動判別)
            this.Texture2D.SetPixel (x, size - 1 - y, color); // 色を描き込む
            yield return null;
        }
    }
    this.Texture2D.Apply ();
    this.Texture2D.filterMode = FilterMode.Point;
    this.Thumbnail.sprite = this.Sprite = Sprite.Create (this.Texture2D, new Rect (0, 0, size, size), new Vector2 (0.5f, 0.5f));
    this.Thumbnail.gameObject.SetActive (true); // サムネイルを表示
    this.Loading.SetActive (false); // クルクルを非表示
}

// 自分が消えるときには、作ったデータも消す
private void OnDestroy () {
    if (this.Texture2D) { Destroy (this.Texture2D); }
    if (this.Sprite) { Destroy (this.Sprite); }
}

環境

  • unity 2018.4.0f1
0
0
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
0
0