我想在unity中 rawimage 上绘制一条2d的折线,不使用linerender 请写出完整脚本
时间: 2023-02-07 14:52:46 浏览: 178
绘制折线图
3星 · 编辑精心推荐
好的,这是在 Unity 中使用脚本在 RawImage 上绘制 2D 折线的完整脚本:
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DrawLine : MonoBehaviour
{
public RawImage rawImage; // 将 RawImage 拖入到这个字段中
public Color lineColor; // 线条的颜色
public float lineThickness; // 线条的粗细
public List<Vector2> linePoints; // 线条的点的列表
void Start()
{
Draw();
}
void Draw()
{
Texture2D texture = new Texture2D(rawImage.texture.width, rawImage.texture.height); // 创建一个新的纹理
texture.SetPixels(rawImage.texture.GetPixels()); // 复制原来 RawImage 的纹理
for (int i = 0; i < linePoints.Count - 1; i++)
{
DrawLine(linePoints[i], linePoints[i + 1], lineColor, lineThickness, texture);
}
texture.Apply(); // 应用更改
rawImage.texture = texture; // 将新的纹理赋值给 RawImage
}
void DrawLine(Vector2 start, Vector2 end, Color color, float thickness, Texture2D texture)
{
int x0 = (int)start.x;
int y0 = (int)start.y;
int x1 = (int)end.x;
int y1 = (int)end.y;
int dx = Mathf.Abs(x1 - x0);
int dy = Mathf.Abs(y1 - y0);
int sx = x0 < x1 ? 1 : -1;
int sy = y0 < y1 ? 1 : -1;
int err = dx - dy;
int e2;
while (true)
{
for (int x = -thickness / 2; x <= thickness / 2; x++)
{
for (int y = -thickness / 2; y <= thickness / 2; y++)
{
texture.SetPixel(x0 + x, y0 + y, color);
}
}
if (x0 == x1 && y0 == y1)
{
break;
}
e2 = 2 * err;
if (e2 > -dy)
{
err -= dy;
x0 += sx;
}
if (e2 < dx)
{
err += dx;
y0 += sy;
}
}
}
}
```
需要注意
阅读全文