using System.Linq;
using UnityEngine;
///
/// 画板
///
public class PaintBoard : MonoBehaviour
{
//当画笔移动速度很快时,为了不出现断断续续的点,所以需要对两个点之间进行插值,lerp就是插值系数
[Range(0, 1)]
public float lerp = 0.05f;
//初始化背景的图片
public Texture2D initailizeTexture;
//当前背景的图片
private Texture2D currentTexture;
//画笔所在位置映射到画板图片的UV坐标
private Vector2 paintPos;
private bool isDrawing = false;//当前画笔是不是正在画板上
//离开时画笔所在的位置
private int lastPaintX;
private int lastPaintY;
//画笔所代表的色块的大小
private int painterTipsWidth = 30;
private int painterTipsHeight = 15;
//当前画板的背景图片的尺寸
private int textureWidth;
private int textureHeight;
//画笔的颜色
private Color32[] painterColor;
private Color32[] currentColor;
private Color32[] originColor;
private void Start()
{
//获取原始图片的大小
Texture2D originTexture = GetComponent().material.mainTexture as Texture2D;
textureWidth = originTexture.width;//1920
textureHeight = originTexture.height;//1080
//设置当前图片
currentTexture = new Texture2D(textureWidth, textureHeight, TextureFormat.RGBA32, false, true);
currentTexture.SetPixels32(originTexture.GetPixels32());
currentTexture.Apply();
//赋值给黑板
GetComponent().material.mainTexture = currentTexture;
//初始化画笔的颜色
painterColor = Enumerable.Repeat(new Color32(255, 0, 0, 255), painterTipsWidth * painterTipsHeight).ToArray();
}
private void LateUpdate()
{
if (Input.GetKeyUp(KeyCode.Space))
{
currentTexture.ClearRequestedMipmapLevel();
currentTexture.Apply();
}
//计算当前画笔,所代表的色块的一个起始点
int texPosX = (int)(paintPos.x * (float)textureWidth - (float)(painterTipsWidth / 2));
int texPosY = (int)(paintPos.y * (float)textureHeight - (float)(painterTipsHeight / 2));
if (isDrawing)
{
//改变画笔所在的块的像素值
currentTexture.SetPixels32(texPosX, texPosY, painterTipsWidth, painterTipsHeight, painterColor);
//如果快速移动画笔的话,会出现断续的现象,所以要插值
if (lastPaintX != 0 && lastPaintY != 0)
{
int lerpCount = (int)(1 / lerp);
for (int i = 0; i <= lerpCount; i++)
{
int x = (int)Mathf.Lerp((float)lastPaintX, (float)texPosX, lerp);
int y = (int)Mathf.Lerp((float)lastPaintY, (float)texPosY, lerp);
currentTexture.SetPixels32(x, y, painterTipsWidth, painterTipsHeight, painterColor);
}
}
currentTexture.Apply();
lastPaintX = texPosX;
lastPaintY = texPosY;
}
else
{
lastPaintX = lastPaintY = 0;
}
}
///
/// 设置当前画笔所在的UV位置
///
///
///
public void SetPainterPositon(float x, float y)
{
paintPos.Set(x, y);
}
///
/// 画笔当前是不是在画画
///
public bool IsDrawing
{
get
{
return isDrawing;
}
set
{
isDrawing = value;
}
}
///
/// 使用当前正在画板上的画笔的颜色
///
///
public void SetPainterColor(Color32 color)
{
if (!painterColor[0].IsEqual(color))
{
for (int i = 0; i < painterColor.Length; i++)
{
painterColor[i] = color;
}
}
}
}
public static class MethodExtention
{
///
/// 用于比较两个Color32类型是不是同种颜色
///
///
///
///
public static bool IsEqual(this Color32 origin, Color32 compare)
{
if (origin.g == compare.g && origin.r == compare.r)
{
if (origin.a == compare.a && origin.b == compare.b)
{
return true;
}
}
return false;
}
}