制作圆形Image

思路

  1. 绘制圆 ,使用多个三角形组合在一起近似一个圆
  2. 单位圆上的点使用(Cosx,Sinx)表示
  3. sprite的uv映射到单位圆上

点到UV的映射规律

Sprite的外部uv 为 (x y z w ) 原点为 (x,y) 宽度为z-x 高度为w-y

单位圆上的点为(CosA,SinA)

uv坐标 = (x,y) + (CosA*(z-x)/2+(z-x)/2 ,SinA*(w-y)/2+(w-y)/2);

例如 圆上的点为(1,0) uv为(0,0.1,1)

对应的uv为 (0,0) + (1*(1-0)/2+(1-0)/2 ,0*(1-0)/2+(1-0)/2)=(1,0.5)

代码示例

csharp 复制代码
using UnityEngine;
using UnityEngine.Sprites;
using UnityEngine.UI;
public class ImageCircle : Image
{
    protected override void OnPopulateMesh(VertexHelper toFill)
    {
        toFill.Clear();//清除顶点

        Vector4 SpriteUV = overrideSprite != null ? DataUtility.GetOuterUV(overrideSprite) : Vector4.zero;
        Vector2 UVSize = new Vector2(SpriteUV.z - SpriteUV.x, SpriteUV.w - SpriteUV.y);//获取精灵uv 宽高
        Vector2 UVOrigion = new Vector2(SpriteUV.x, SpriteUV.y);//uv原点
        Vector2 UVHalfSize = UVSize / 2;
        Vector2 CenterUV = UVOrigion + UVHalfSize;

        Vector2 roundPoint = rectTransform.rect.center;//圆心
        toFill.AddVert(roundPoint, color, CenterUV);

        float width = rectTransform.rect.width;//image 矩形框的宽度
        float height = rectTransform.rect.height;
        float radius = width > height ? height / 2 : width / 2;//半径 取较小值

        int triangleCount = 100;//组成圆的三角形数量
        float singleAngle = 2 * Mathf.PI / triangleCount;//单个三角形顶点角度

        Vector2 pointInCircle;
        Vector2 pointToUV;
        float currentAngle;

        for (int i = 0; i < triangleCount + 1; i++)//获取圆上的点 圆上的点比三角形数量多1
        {
            currentAngle = i * singleAngle;//当前角度

            pointInCircle = new Vector2(Mathf.Cos(currentAngle), Mathf.Sin(currentAngle));//单位圆上的点

            pointToUV = UVOrigion +
                new Vector2(pointInCircle.x * UVHalfSize.x + UVHalfSize.x,
                pointInCircle.y * UVHalfSize.y + UVHalfSize.y);//点对应的uv

            toFill.AddVert(roundPoint + pointInCircle * radius, color, pointToUV);
        }

        for (int i = 0; i < triangleCount; i++)//绘制三角形
        {
            toFill.AddTriangle(i + 1, 0, i + 2);
        }
    }
}

参考

Unity用OnPopulateMesh绘制自定义圆形遮罩超详解

相关推荐
WarPigs7 小时前
Unity光照笔记
笔记·unity·游戏引擎
神码编程11 小时前
【Unity】 HTFramework框架(六十五)ScrollList滚动数据列表
unity·游戏引擎·ugui
DanmF--12 小时前
Protobuf工具
网络·unity·游戏引擎·游戏程序
敲代码的 蜡笔小新15 小时前
【行为型之迭代器模式】游戏开发实战——Unity高效集合遍历与场景管理的架构精髓
unity·设计模式·c#·迭代器模式
敲代码的 蜡笔小新1 天前
【行为型之命令模式】游戏开发实战——Unity可撤销系统与高级输入管理的架构秘钥
unity·设计模式·架构·命令模式
驰愿2 天前
ET EntityRef EntityWeakRef 类分析
unity·et
敲代码的 蜡笔小新2 天前
【行为型之中介者模式】游戏开发实战——Unity复杂系统协调与通信架构的核心秘诀
unity·设计模式·c#·中介者模式
敲代码的 蜡笔小新2 天前
【行为型之解释器模式】游戏开发实战——Unity动态公式解析与脚本系统的架构奥秘
unity·设计模式·游戏引擎·解释器模式
敲代码的 蜡笔小新2 天前
【行为型之观察者模式】游戏开发实战——Unity事件驱动架构的核心实现策略
观察者模式·unity·设计模式·c#
向宇it2 天前
【unity游戏开发——编辑器扩展】使用EditorGUI的EditorGUILayout绘制工具类在自定义编辑器窗口绘制各种UI控件
开发语言·ui·unity·c#·编辑器·游戏引擎