Unity 制作签名功能——使用LineRender实现UI上签名效果

本文介绍如何在Unity中实现UI签名功能。通过对比修改图片像素点(导致马赛克效果)和使用LineRenderer实现3D签名的2D效果,详细讲解了LineRenderer方法的实现过程,包括脚本、 hierarchy窗口设置、相机截图以及颜色调整等关键步骤,以满足全屏签名和截取特定区域的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言:项目中需要做一个签名的功能,同时需要两个两个屏幕进行显示,但是都是在UI上,从网上查了大量资料。

找到两种方法:

  1. 修改图片像素点       但是是马赛克效果,不满足需求
  2. 使用LineRenderer 的3D签名制作出2D效果

修改像素点:

先上代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Test : ObjBase
{

    public GameObject m_obj;
    private Texture2D m_tex;
    public Color m_color;
    public int size = 3;
    private Color[] m_textureColorsStart;


    public RawImage showImg;
    void Start()
    {
        if (Display.displays.Length > 1)
            Display.displays[1].Activate();
        if (Display.displays.Length > 2)
            Display.displays[2].Activate();
        m_tex = m_obj.GetComponent<MeshRenderer>().material.mainTexture as Texture2D;
        //从纹理中获取像素颜色
        m_textureColorsStart = m_tex.GetPixels();
        Debug.Log(m_tex.name);
    }


    void Update()
    {
        //Vector3 oldPos=Vector3.zero;
        //oldPos = Input.mousePosition;
        //Ray ray = uiCam.ScreenPointToRay(Input.mousePosition);
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if (Input.GetMouseButton(0))
        {
            // float m_magnitude = (Input.mousePosition - oldPos).magnitude;
            // Vector3 dir = Input.mousePosition - oldPos;  
            if (Physics.Raycast(ray, out hit))
            {
                //在碰撞位置处的UV纹理坐标。
                Vector2 pixelUV = hit.textureCoord;
                //以像素为单位的纹理宽度
                pixelUV.x *= m_tex.width;
                pixelUV.y *= m_tex.height;
                //贴图UV坐标以右上角为原点
                for (float i = pixelUV.x - 1; i < pixelUV.x + size; i++)
                {
                    for (float j = pixelUV.y - 1; j < pixelUV.y + size; j++)
                    {
                        m_tex.SetPixel((int)i, (int)j, m_color);
                    }
                }
                Debug.Log(pixelUV);
                m_tex.Apply();
                showImg.texture = m_tex;
            }
        }
        if (Input.GetKeyDown(KeyCode.Space))
        {
            //还原
            m_tex.SetPixels(m_textureColorsStart);
            m_tex.Apply();
        }


        //在处理鼠标按下的记录下位置,抬起的时候记录下位置,取2个位置中间的位置
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值