制作圆形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绘制自定义圆形遮罩超详解

相关推荐
LONGZETECH7 小时前
无人机实训高成本痛点解法:虚拟仿真实现 70% 耗材损耗下降
大数据·算法·unity·架构·无人机
五仁烧饼20 小时前
Unity Addressables 静默资源策略
游戏·unity·addressables
fanfan_hongyun1 天前
unity 与cad 坐标系映射
unity·游戏引擎
神码编程1 天前
【Unity】 HTFramework框架(七十)MultiChoiceDropdown可多选的下拉菜单
unity·游戏引擎·ugui·dropdown·下拉菜单
淡海水1 天前
15-07-YooAsset面试篇-Unity性能优化与内存管理
java·unity·面试·性能优化·c#·游戏引擎
zhchyun20082 天前
# 【Unity UI 进阶】仿 Element UI 打造企业级 Unity UI 组件库(03)
unity
淡海水3 天前
15-02-YooAsset面试篇-Unity架构设计与源码
java·unity·面试·c#·游戏引擎·yooasset
郝学胜-神的一滴3 天前
中级OpenGL教程 030:gl_FragCoord解锁区域渲染与深度可视化新姿势
c++·unity·游戏引擎·图形渲染·unreal engine·opengl
ellis19703 天前
u3d插件xLua[四]Lua访问C#源码分析,反射,生成代码
unity