Unity 读取UGUI Spirte 剪裁部分显示区域,保存为新的Png*

本文介绍了一个Unity脚本,用于读取UGUISprite的特定剪裁区域,并将其保存为新的PNG图片。该脚本通过计算偏移量和尺寸,精确地从原始纹理中提取所需的部分。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值