Unity开发笔记:将Texture2D裁剪出指定圆角用来输出png等图片

学习记录整理,自用,也希望能帮助到有相同需求的人。
圆角原理见大佬的博客:
圆角原理

简单来说就是将图片分成四个区域,找出拐角处的拐子的设置为透明
![](https://img-blog.csdnimg.cn/a788825545614816895a9cca42ddc4a9.png
在这里插入图片描述
如图,找到四个红色区域外边的白色区域 设置为透明即可。

注意texture本身应该为支持透明的格式如TextureFormat.RGBA32,且导出为png等支持透明的格式(比如jpg不支持透明)。

函数代码:

    void myBorder(Texture2D texture, float radius)
    {
        Vector2 a = new Vector2(0f, 0f);
        Vector2 b = new Vector2(0.5f - radius, 0.5f - radius);
        for (float i = 0; i < texture.width; ++i)
        {
            for (float j = 0; j < texture.height; ++j)
            {
                a.x = Math.Abs((i - texture.width / 2) / texture.width);
                a.y = Math.Abs((j - texture.height / 2) / texture.height);
                //(Vector2.Distance(a, b) > radius && a.x :去除中间十字形区域
                //a.x > (0.5f - radius) && a.y > (0.5f - radius)去除十字形区域间的四个圆角
                if (Vector2.Distance(a, b) > radius && a.x > (0.5f - radius) && a.y > (0.5f - radius))
                {
                    //剩下的就是要设置透明的区域
                    texture.SetPixel((int)i, (int)j, Color.clear);
                }
            }
        }
    }

上述代码中Radius为圆角参数,区间为[0,0.5],数值越大圆角越大

一个简单的调用实例:

        // 创建一个新的 Texture2D 来保存截屏数据
        Texture2D uiTexture = new Texture2D((int)width, (int)height, TextureFormat.RGBA32, false);
        uiTexture.ReadPixels(new Rect(0, 0, width, height), 0, 0);
        myBorder(uiTexture, 0.065f);

        // 将 Texture2D 保存为图片文件
        byte[] imageBytes = uiTexture.EncodeToPNG();
        string path = "Assets/Textures/UI/20230803/4.png"; 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值