LoginSignup
2
2

More than 5 years have passed since last update.

Unity + NGUI で任意の形に表示領域を制限する

Last updated at Posted at 2017-03-25

はじめに

  • NGUI の UIPanel の Clipping 機能を使うと、子要素の表示領域を制限することができる。
  • 表示領域は幅と高さを設定して四角く指定するか、テクスチャを渡してアルファ値で透過非透過を指定できる。
  • 今回はテクスチャを動的に生成して UIPanel に渡して Clipping することで任意の形に表示領域を制限してみる。

環境

  • Unity 5.5.2f
  • NGUI 3.11.2

コード

using UnityEngine;

public class Cliptest : MonoBehaviour
{
    public UIPanel panel;
    public int width = 300;
    public int height = 300;

    void Start ()
    {
        ClipTexture ();
    }

    public void ClipTexture ()
    {
        // テクスチャの作成
        var t = new Texture2D (width, height, TextureFormat.ARGB32, false);

        // テクスチャの設定
        t.filterMode = FilterMode.Point;
        t.wrapMode = TextureWrapMode.Clamp;

        // 隠す部分の色
        var mask = new Color (0, 0, 0, 0);
        // 表示する部分の色
        var transparent = new Color (1, 1, 1, 1);

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                if (y == 0 || x == 0 || y == height - 1 || x == width - 1)
                {
                    // テクスチャの端が透過だと端の座標を含んでいる要素が全て表示されてしまう
                    // 端を非透過にすることでテクスチャの範囲できれいに隠すことができる
                    t.SetPixel (x, y, mask);
                }
                else if ((x < width / 2 && y < height / 2) || (x >= width / 2 && y >= height / 2))
                {
                    t.SetPixel (x, y, mask);
                }
                else
                {
                    t.SetPixel (x, y, transparent);
                }
            }
        }

        // テクスチャへの変更の適用
        t.Apply ();

        // テクスチャでクリッピング
        panel.clipTexture = t;
        panel.clipping = UIDrawCall.Clipping.TextureMask;
    }
}

実行結果

Clipping 前

スクリーンショット 2017-03-25 9.31.26.png

Clipping 後

スクリーンショット 2017-03-25 9.31.40.png

Clipping 後の Inspector

スクリーンショット 2017-03-25 9.32.04.png

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