我想在unity中 rawimage 上绘制一条2d的折线,不使用linerender 请写出完整脚本

该脚本展示了如何在Unity中使用C#脚本来在RawImage组件上绘制2D折线。它涉及到颜色设置、线条厚度调整以及通过Vector2点列表定义线条路径。首先,脚本创建一个新纹理,然后遍历点列表,用指定颜色和粗细画出线条,并将新纹理应用到RawImage上。
摘要由CSDN通过智能技术生成

好的,这是在 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 &amp;&amp; y0 == y1)
            {
                break;
            }

            e2 = 2 * err;
            if (e2 > -dy)
            {
                err -= dy;
                x0 += sx;
            }

            if (e2 < dx)
            {
                err += dx;
                y0 += sy;
            }
        }
    }
}

需要注意

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值