前言:项目中需要做一个签名的功能,同时需要两个两个屏幕进行显示,但是都是在UI上,从网上查了大量资料。
找到两种方法:
- 修改图片像素点 但是是马赛克效果,不满足需求
- 使用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个位置中间的位置