Unity使用RawImage实现图片百叶窗显示

**

前言

**
最近接到一个项目,非得要百叶窗切换图片,于是乎想着快速开发的原则,先去求助百度,然后最后基本上都指定到一个大佬写的shader,然后我就下载下来尝试下,结果不是很理想,可能是我不会shader的原因,效果不是想要的,而且,似乎用代码不好控制,于是我想,要不改下算了,对,想到就去改,嗯。。。。好吧,我根本不会shader,还是写代码吧,想到百叶窗的原理,估计还是shader要快捷,算了,用rawImage也是可以设置uv的嘛

**

原理

**
拿到一张图,想把它百叶窗,那就是切割呗,设置好,要切割的xy,然后生成对应数量的raw,然后设置uv,这里的一开始的位置约束,我直接用了group组件来约束,然后在运行的时候进行关闭,然后对每个raw进行动画操作,动画无非就是上下,左右移动,然后就是基于哪边进行移动,所以就出了四个变量,锚点xy,移动的横竖,再加上一个速度变量,由于后期需要,我还加了一个是否消失的变量,消失的时候客户还要随机两个样式,锤死他,难为人,但还是做了,这里不细说,有兴趣的可以看代码

上代码

主要控制类

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

public class BaiYeChuang : MonoBehaviour {

    public Vector2Int BSize;
    public float speed = 1;
    public GameObject pre;

    public bool needLoadStart = false;
    public Texture2D loadTex;
    private GridLayoutGroup group;
    private RectTransform rectTransform;

    private RawImage[] raws;
    private BYCItem[] items;

    //private int count = 0,okNow = 0;
    
    private void Start()
    {
        if(needLoadStart)
            SetIt();
    }

    public void Play()
    {
        if(!group.enabled)
            group.enabled = true;
        foreach (var item in items)
        {
            item.Play(0,0,true,false,speed);
        }
        CancelInvoke();
        Invoke("HideGroup", 0.05f);
    }

    //public void SetOkNow()
    //{
    //    okNow++;
    //}

    public void PlayX()
    {
        if (!group.enabled)
            group.enabled = true;
        bool it = Random.Range(0,2) == 0;
        foreach (var item in items)
        {
            it = !it;
            item.Play(it?0:1, it ? 1 : 0, it, it, speed);
        }
        CancelInvoke();
        Invoke("HideGroup", 0.05f);
    }

    public void PlayX(Texture2D tx)
    {
        if (!group.enabled)
            group.enabled = true;
        bool it = false;
        bool ll = Random.Range(0, 2) == 0;
        foreach (var item in items)
        {
            it = !it;
            item.Play(it ? 0 : 1, 0, true, false, speed,tx, ll);
        }
        CancelInvoke();
        Invoke("HideGroup", 0.05f);
    }

    private void HideGroup()
    {
        group.enabled = false;
    }

    public void PlayY()
    {
        if (!group.enabled)
            group.enabled = true;
        foreach (var item in items)
        {
            item.Play(0, 0, false, true, speed);
        }
        CancelInvoke();
        Invoke("HideGroup", 0.05f);
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Alpha1))
        {
            Play();
        }
        if (Input.GetKeyDown(KeyCode.Alpha2))
        {
            PlayX();
        }
        if (Input.GetKeyDown(KeyCode.Alpha3))
        {
            PlayY();
        }
    }

    public void SetSize()
    {
        for (int i = 0,j = transform.childCount; i < j; i++)
        {
            DestroyImmediate(transform.GetChild(0).gameObject);
        }
        float x = rectTransform.sizeDelta.x / BSize.x;
        float y = rectTransform.sizeDelta.y / BSize.y;
        group.constraintCount = BSize.x;
        group.cellSize = new Vector2(x, y);
        for (int i = 0,j = BSize.x * BSize.y; i < j; i++)
        {
            Instantiate(pre, transform);
        }
        //group.enabled = false;
    }

    [ContextMenu("更换图片")]
    public void SetTex()
    {
        int length = transform.childCount;
        float sizeZx = 1f / BSize.x;
        float sizeZy = 1f / BSize.y;
        int x,y = 0;
        for (int i = 0; i < length; i++)
        {
            y = i % BSize.x;
            x = i / BSize.x;
            raws[i].GetComponent<BYCItem>().Init(group.cellSize,new Vector2(y * sizeZx,1 - x * sizeZy - sizeZy), new Vector2(sizeZx,sizeZy),loadTex);
            //raws[i].rectTransform.sizeDelta = Vector2.zero;
            //raws[i].texture = loadTex;
        }
    }

    public void SetTexSample(Texture2D tex)
    {
        if(tex != null)
            loadTex = tex;
        foreach (var item in raws)
        {
            item.texture = loadTex;
        }
    }

    private void GetRaws()
    {
        raws = new RawImage[BSize.x * BSize.y];
        items = new BYCItem[BSize.x * BSize.y];
        for (int i = 0; i < raws.Length; i++)
        {
            raws[i] = transform.GetChild(i).GetComponent<RawImage>();
            items[i] = transform.GetChild(i).GetComponent<BYCItem>();
        }
    }

    [ContextMenu("设置预制体")]
    public void SetIt()
    {
        group = GetComponent<GridLayoutGroup>();
        rectTransform = GetComponent<RectTransform>();
        SetSize();
        GetRaws();
        SetTex();
    }

    public void ResetInfo()
    {
        SetSize();
        GetRaws();
        SetTex();
    }

    public void ClearTexs()
    {
        foreach (var item in raws)
        {
            item.color = Color.clear;
            item.texture = null;
        }
    }
}

个体运动类

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

public class BYCItem : MonoBehaviour
{
    public RawImage raw;
    private readonly float playTime = 1;
    private Vector2 size, uvXY, uvWH;
    private Coroutine cor;
    private float moveSpeed;
    private bool left, down, heng, shu = false;
    private bool backLeft, backDown, backHeng, backShu = false;

    private float tim = 0;
    private bool run = false,backRun = false,backRun1 = false;
    //private BaiYeChuang byc;

    private GridLayoutGroup grid;
    private Texture2D nextT;
    

    public void Init(Vector2 _size, Vector2 _uvXY, Vector2 _uvWH,Texture2D _tex)
    {
        size = _size;
        uvXY = _uvXY;
        uvWH = _uvWH;
        raw.uvRect = new Rect(uvXY, uvWH);
        raw.rectTransform.sizeDelta = Vector2.zero;
        grid = GetComponentInParent<GridLayoutGroup>();
        raw.texture = _tex;
        if(_tex == null)
            raw.color = Color.clear;
    }

    public void Play(int x, int y, bool xdo, bool ydo ,float speed)
    {
        moveSpeed = speed;
        raw.rectTransform.pivot = new Vector2(x, y);
        left = x == 1;
        down = y == 1;
        heng = xdo;
        shu = ydo;
        //if (cor == null)
        //    cor = StartCoroutine(PlayAnysc(xdo, ydo));
        if(cor == null)
            cor = StartCoroutine(ResetPivotAnsyc());
    }

    public void Play(int x, int y, bool xdo, bool ydo, float speed,Texture2D nextTex,bool rand)
    {
        moveSpeed = speed;
        raw.rectTransform.pivot = new Vector2(x, y);
        left = x == 1;
        down = y == 1;
        heng = xdo;
        shu = ydo;
        nextT = nextTex;
        //if (cor == null)
        //    cor = StartCoroutine(PlayAnysc(xdo, ydo));
        if (!backRun)
        {
            backLeft = false;
            backDown = true;
            backHeng = false;
            backShu = true;
            int a = Random.Range(0, 2);
            backRun = rand;
            backRun1 = !backRun;
            tim = 1;
        }
            
    }
    

    IEnumerator ResetPivotAnsyc()
    {
        raw.enabled = false;
        if (nextT != null)
            raw.texture = nextT;
        //grid.enabled = true;
        raw.rectTransform.sizeDelta = Vector2.zero;
        raw.color = Color.white;
        yield return new WaitForSeconds(0.1f);
        //grid.enabled = false;
        raw.enabled = true;
        if (!run)
            run = true;
        cor = null;
    }

    IEnumerator PlayAnysc(bool x, bool y)
    {
        float ti = 0;
        //yield return 0;
        while (ti < playTime)
        {
            ti += Time.deltaTime * moveSpeed;
            yield return 0;
            raw.rectTransform.sizeDelta = new Vector2(x ? ti * size.x : size.x, y ? ti * size.y : size.y);
            raw.uvRect = new Rect(new Vector2(left ? uvXY.x + (1 - ti) * uvWH.x : uvXY.x,down ? uvXY.y + (1 - ti) * uvWH.y:uvXY.y), new Vector2(x ? uvWH.x * ti : uvWH.x, y ? uvWH.y * ti : uvWH.y));
        }
        raw.rectTransform.sizeDelta = size;
        raw.uvRect = new Rect(uvXY, uvWH);
        cor = null;
    }


    private void LateUpdate()
    {
        if (run)
        {
            tim += Time.deltaTime * moveSpeed;
            raw.rectTransform.sizeDelta = new Vector2(heng ? tim * size.x : size.x, shu ? tim * size.y : size.y);
            raw.uvRect = new Rect(new Vector2(left ? uvXY.x + (1 - tim) * uvWH.x : uvXY.x, down ? uvXY.y + (1 - tim) * uvWH.y : uvXY.y), new Vector2(heng ? uvWH.x * tim : uvWH.x, shu ? uvWH.y * tim : uvWH.y));
            if(tim >= 1)
            {
                raw.rectTransform.sizeDelta = size;
                raw.uvRect = new Rect(uvXY, uvWH);
                run = false;
                tim = 0;
                //grid.enabled = true;
            }
        }

        if (backRun)
        {
            tim -= Time.deltaTime * moveSpeed;
            raw.rectTransform.sizeDelta = new Vector2(backHeng ? tim * size.x : size.x, backShu ? tim * size.y : size.y);
            raw.uvRect = new Rect(new Vector2(backLeft ? uvXY.x + (1 - tim) * uvWH.x : uvXY.x, backDown ? uvXY.y + (1 - tim) * uvWH.y : uvXY.y), new Vector2(backHeng ? uvWH.x * tim : uvWH.x, backShu ? uvWH.y * tim : uvWH.y));
            if (tim <= 0)
            {
                raw.rectTransform.sizeDelta = Vector2.zero;
                backRun = false;
                tim = 0;
                if (cor == null)
                    cor = StartCoroutine(ResetPivotAnsyc());
            }
        }

        if (backRun1)
        {
            tim -= Time.deltaTime * moveSpeed;
            if(raw.texture != null)
                raw.color = Color.Lerp(Color.clear, Color.white, tim);
            if (tim <= 0)
            {
                raw.rectTransform.sizeDelta = Vector2.zero;
                backRun1 = false;
                tim = 0;
                if (cor == null)
                    cor = StartCoroutine(ResetPivotAnsyc());
            }
        }
    }
    

}

上效果

Unity使用RawImage实现图片百叶窗显示_第1张图片
Unity使用RawImage实现图片百叶窗显示_第2张图片
Unity使用RawImage实现图片百叶窗显示_第3张图片
这些其实就是改变那四个变量,得到的效果,哦,图片是从百度上搜到的壁纸,不太清楚有没有版权。。。

unity包下载

我用的2019.3.5,所以2018.3之前的预制体可能会有问题,大家可以自己进行新的预制体制作
链接:https://pan.baidu.com/s/1QdvSXsPX1DC9qoz9-bjanA
提取码:i3cu
Unity使用RawImage实现图片百叶窗显示_第4张图片
Unity使用RawImage实现图片百叶窗显示_第5张图片

你可能感兴趣的:(unity开发)