原理:
利用 Graphic 类重写 OnPopulateMesh 方法类绘制自定义顶点的面片从而组成一条线。
MaskableGraphic 类继承自 Graphic,并且可以实现“可遮罩图形”,方便在列表中使用。
绘制图形API:
// 添加顶点,第一个添加的顶点索引为0,第二个添加的顶点为1,依次.....
AddVert
// 绘制三角形,GPU绘制时会按照输入的顶点下标的顺序绘制一个三角形
AddTriangle
// 添加一个矩形
AddUIVertexQuad
// 批量添加顶点
AddUIVertexStream
// 批量添加三角形顶点,长度必须是3的倍数
AddUIVertexTriangleStream
组件功能说明:
1、设置线段宽度
2、切换曲线和直线绘制模式
3、在曲线模式下,可以控制曲线的片段数量
4、实时刷新,根据目标点的位置实时更新线条
具体实现可直接复制代码使用,具体实现已添加备注。
完整代码:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace XLine
{
/// <summary>
/// VertexHelper 扩展类型
/// </summary>
static class VertexHelperEx
{
#region Bezier
class Bezier
{
private Vector2 _point0, _point1, _point2, _point3;
/// <summary>
///
/// </summary>
/// <param name="p"></param>
/// <exception cref="ArgumentException">x0,y0,x1,y1,x2,y2,x3,y3</exception>
public Bezier(params float[] p)
{
if (p.Length < 8)
{
throw new ArgumentException("参数数量错误,需要8个参数(4个Vector2)");
}
_point0 = new Vector2(p[0], p[1]);
_point1 = new Vector2(p[2], p[3]);
_point2 = new Vector2(p[4], p[5]);
_point3 = new Vector2(p[6], p[7]);
}
public Bezier(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3)
{
_point0 = p0;
_point1 = p1;
_point2 = p2;
_point3 = p3;
}
public float X(float t)
{
var it = 1 - t;
return it * it * it * _point0.x +
3 * it * it * t * _point1.x +
3 * it * t * t * _point2.x +
t * t * t * _point3.x;
}
public float Y(float t)
{
var it = 1 - t;
return it * it * it * _point0.y +
3 * it * it * t * _point1.y +
3 * it * t * t * _point2.y +
t * t * t * _point3.y;
}
public float SpeedX(float t)
{
var it = 1 - t;
return -3 * _point0.x * it * it +
3 * _point1.x * it * it -
6 * _point1.x * it * t +
6 * _point2.x * it * t -
3 * _point2.x * t * t +
3 * _point3.x * t * t;
}
public float SpeedY(float t)
{
var it = 1 - t;