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

学习记录整理,自用,也希望能帮助到有相同需求的人。

圆角原理见大佬的博客:
圆角原理

简单来说就是将图片分成四个区域,找出拐角处的拐子的设置为透明

![](https://img-blog.csdnimg.cn/a788825545614816895a9cca42ddc4a9.png

如图,找到四个红色区域外边的白色区域 设置为透明即可。

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

函数代码:

csharp 复制代码
    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],数值越大圆角越大

一个简单的调用实例:

csharp 复制代码
        // 创建一个新的 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"; 
相关推荐
快乐觉主吖10 小时前
Unity网络通信的插件分享,及TCP粘包分包问题处理
tcp/ip·unity·游戏引擎
迷曳14 小时前
24、鸿蒙Harmony Next开发:不依赖UI组件的全局自定义弹出框 (openCustomDialog)
dialog·前端·ui·harmonyos·鸿蒙
R-G-B15 小时前
【27】MFC入门到精通——MFC 修改用户界面登录IP IP Address Control
tcp/ip·ui·mfc·mfc 用户界面登录·mfc ip登录·mfc address登录
布兰妮甜18 小时前
Adobe Photoshop:数字图像处理的终极工具指南
图像处理·ui·adobe·photoshop
orange_の_呜1 天前
Adobe illustrator、klayout绘制光刻图及其尺寸映射
ui·adobe·illustrator
共享ui设计和前端开发1 天前
数字孪生技术引领UI前端设计新高度:跨平台数据一致性的可视化
ui
erxij2 天前
【游戏引擎之路】登神长阶(十八):3天制作Galgame引擎《Galplayer》——无敌之道心
游戏引擎
lizz312 天前
GAMES101 lec2-数学基础1(线性代数)
线性代数·游戏引擎·图形渲染
啊基米德2 天前
lua(xlua)基础知识点记录一
unity·lua·xlua
夜色。2 天前
Unity Android Logcat插件 输出日志中文乱码解决
android·unity