うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】Image を 複製して表示

画像を上下左右に複製して表示できる どこで使えるか分からないが、とりあえず作ってみたので・・・

サイズの大きい左右上下対象の画像をサイズ半分で使える・・・ 別に反転しておけばいいだけの話ですが・・・

f:id:hacchi_man:20200423033416p:plain

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[RequireComponent(typeof(Image))]
public class DuplicateImage : BaseMeshEffect
{
    private enum Direction
    {
        Top,
        Bottom,
        Left,
        Right,
    }

    [SerializeField]
    private Direction duplicateDirection = Direction.Left;

    private List<UIVertex> _vertexList = new List<UIVertex>();
    
    public override void ModifyMesh(VertexHelper helper)
    {
        var cacheRect = transform as RectTransform;
        _vertexList.Clear();
        helper.GetUIVertexStream(_vertexList);
        
        var count = _vertexList.Count;
        for (var i = 0; i < count; ++i)
        {
            var vertex = _vertexList[i];
            var vertexDuplicate = _vertexList[i];
            switch (duplicateDirection)
            {
                case Direction.Bottom:
                    vertex.position.y += cacheRect.rect.height / 2f;
                    vertexDuplicate.position.y = vertex.position.y * -1 - Mathf.LerpUnclamped(-cacheRect.rect.height, cacheRect.rect.height, cacheRect.pivot.y);
                    break;
                case Direction.Top:
                    vertex.position.y -= cacheRect.rect.height / 2f;
                    vertexDuplicate.position.y = vertex.position.y * -1 - Mathf.LerpUnclamped(-cacheRect.rect.height, cacheRect.rect.height, cacheRect.pivot.y);
                    break;
                case Direction.Right:
                    vertex.position.x -= cacheRect.rect.width / 2f;
                    vertexDuplicate.position.x = vertex.position.x * -1 - Mathf.LerpUnclamped(-cacheRect.rect.width, cacheRect.rect.width, cacheRect.pivot.x);
                    break;
                case Direction.Left:
                    vertex.position.x += cacheRect.rect.width / 2f;
                    vertexDuplicate.position.x = vertex.position.x * -1 - Mathf.LerpUnclamped(-cacheRect.rect.width, cacheRect.rect.width, cacheRect.pivot.x);
                    break;
            }

            _vertexList[i] = vertex;
            _vertexList.Add(vertexDuplicate);
        }

        
        helper.Clear();
        helper.AddUIVertexTriangleStream(_vertexList);  
    }
}