将图片一张图切割成多个小图,不仅仅是九宫格

效果如图所示

我这里直接把切割后的图片付给了Button

Unity 图片切割九宫格_数组

被切割的图片属性要做一下设置

 

Unity 图片切割九宫格_数组_02

脚本如下: 

 

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

public class SixImage : MonoBehaviour
{

    //小图的宽和高
    public int m_iMinWidth;
    public int m_iMinHeight;
    //一行有多少个小图
    public int m_iMinPicRowCount = 3;
    //一列有多少个小图
    public int m_iMinPicColumnCount = 3;
    //需要切割的大图
    public Texture2D m_texPlayer;
    //小图数组
    private Texture2D[,] m_texPlayers;

    //切割后的图片
    public Transform transforms;

    void Start()
    {
        m_iMinPicRowCount = 3;
        m_iMinPicColumnCount = 3;
        m_texPlayers = new Texture2D[m_iMinPicRowCount, m_iMinPicColumnCount];

    }

    // Update is called once per frame
    void Update()
    {

    }

    /// <summary>
    /// 切图
    /// </summary>
    /// <param name="i"></param>
    /// <param name="j"></param>
    //切图
    public void DePackTexture(int i, int j)
    {
        //通过大图宽高计算出每次切图的大小
        m_iMinHeight = m_texPlayer.height / m_iMinPicColumnCount;
        m_iMinWidth = m_texPlayer.width / m_iMinPicRowCount;

        int cur_x = i * m_iMinWidth;
        int cur_y = j * m_iMinHeight;
        Texture2D newTexture = new Texture2D(m_iMinWidth, m_iMinHeight);
        for (int m = cur_y; m < cur_y + m_iMinHeight; m++)
        {
            for (int n = cur_x; n < cur_x + m_iMinWidth; n++)
            {
                //核心 通过从大图拿到的像素点赋值给小图
                newTexture.SetPixel(n - cur_x, m - cur_y, m_texPlayer.GetPixel(n, m));
            }
        }
        //Apply一下 更新贴图
        newTexture.Apply();
        //储存到数组
        m_texPlayers[i, j] = newTexture;

    }

    public void button() 
    {
        //切割图片
        for (int i = 0; i < m_iMinPicRowCount; i++)
        {
            for (int j = 0; j < m_iMinPicColumnCount; j++)
            {
                DePackTexture(i, j);
            }
        }


        
        for (int i = 2; i >= 0; i--)
        {
            for (int j= 0; j < 3; j++)
            {
                
                Sprite sprite = Sprite.Create(m_texPlayers[j, i], new Rect(0, 0, m_texPlayers[i, j].width, m_texPlayers[i, j].height), Vector2.zero);
                GameObject go = Resources.Load<GameObject>("Image");
                GameObject g = Instantiate(go);
                g.GetComponent<Image>().sprite = sprite;
                g.transform.SetParent(transforms);

            }
        }


    }
   
}

@Liam:有用→收藏→关注   听说长得好看的人都这么做!