NGUI分割图集

作者:追风剑情 发布于:2020-4-20 12:52 分类:Unity3d

示例:将现有的整张图集重新分割成单张图片

工程截图

1111.png

分割脚本


using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEditor;

[ExecuteInEditMode]
public class SplitAtlas : MonoBehaviour {

	public UIAtlas atlas;
	public Texture2D texture;
	public bool split = false;

	void Update()
	{
		if (!split)
			return;
		split = false;

		List<UISpriteData> list = atlas.spriteList;
		UISpriteData sd;
		for (int i=0; i< list.Count; i++)
		{
			sd = list[i];
			//反转y坐标
			int sdy = texture.height - (sd.y + sd.height);
			//GetPixels()读取像素的顺序是从左到右,从下到上。
			Color[] colors = texture.GetPixels(sd.x, sdy, sd.width, sd.height);

			Texture2D tex = new Texture2D(sd.width, sd.height, TextureFormat.RGBA32, false);
			tex.SetPixels(0, 0, sd.width, sd.height, colors);
			tex.Apply();
			
			Debug.LogFormat("sd.x={0}, sd.y={1}, sd.width={2}, sd.height={3}",
				sd.x, sd.y, sd.width, sd.height);

			string filePath = Path.Combine(Application.streamingAssetsPath, sd.name + ".png");
			SavePNG(filePath, tex);
		}
		AssetDatabase.Refresh();
	}

	//保存Texture2D为png图片
	public void SavePNG(string filePath, Texture2D texture)
	{
		try
		{
			byte[] pngData = texture.EncodeToPNG();
			File.WriteAllBytes(filePath, pngData);
		}
		catch (Exception ex)
		{
			Debug.Log(ex.StackTrace);
		}
	}
}


测试

分割前的整张图集

EnterGameLoading.png

分割后的散图

22222.png

标签: Unity3d

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号