Unity 读取UGUI Spirte 剪裁部分显示区域,保存为新的Png
void splitImage(string icon,string[] offsets)
{
string sourceStr = StringUtils.combine("hero_full/", icon);
Sprite sprite = Resources.Load(sourceStr, typeof(Sprite)) as Sprite;
if (sprite == null)
return;
//要保存的图片宽高
int widht = 256;
int height = 256;
int halfw = widht / 2;
int halfh = height / 2;
//额外需要的偏移量
int offsetx = 0;
int offsety = 0;
if (offsets.Length == 2)
{
offsetx = UtilityFunction.ParseInt(offsets[0]);
offsety = UtilityFunction.ParseInt(offsets[1]);
}
//从图片正中心点开始 截取偏移量的图片
int startx = sprite.texture.width / 2 - halfw - offsetx;
int starty = sprite.texture.height / 2 - halfh - offsety;
//核心代码,新建Texture2D 读取老图要剪裁的区域
Texture2D png = new Texture2D(widht, height, TextureFormat.RGBA32, false);
png.SetPixels(sprite.texture.GetPixels(startx, starty, widht, height));
png.Apply();
//存储图片到指定目录下
string contents = "hero_result";
byte[] bytes = png.EncodeToPNG();
if (!Directory.Exists(contents))
Directory.CreateDirectory(contents);
FileStream file = File.Open(contents + "/"+ icon + ".png", FileMode.Create);
BinaryWriter writer = new BinaryWriter(file);
writer.Write(bytes);
file.Close();
Texture2D.DestroyImmediate(png);
png = null;
}