一:实现思路
首先,要想要一张图片透明,那么应该改变图片的alpha值
其次,我们想要对一张图片的像素点进行操作,那么这个图片应该转换为sprite,且需要勾选读写属性(Read/Write)
最后,创建rawImage的ui对象,将准备好的图片赋予给它
二:场景搭建
三:代码展示
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class EraseImage : MonoBehaviour
{
[Tooltip("显示提示的文本")] public TMP_Text TipsTMPText;
[Tooltip("显示进度的文本")] public TMP_Text ScheduleTMPText;
[Tooltip("需要擦除的图像")] public RawImage target;
private Texture2D replaceTex; //操作像素点的图片
private int sumPixels; //图片的总像素点,用于进度计算
private float fixedPixels; //已经被修改的像素数量,用于进度计算
private int texWidth; //记录图片的宽度
private int texHeight; //记录图片的高度
private int brushSize = 20; //画笔的大小
private Ray ray;
private RaycastHit hit;
private void Awake()
{
Texture2D tempTex = (Texture2D)target.mainTexture;
//创建一个大小和刮刮乐图片一致,rgba格式,不因距离而模糊渲染的texture2d对象
replaceTex = new Texture2D(tempTex.width, tempTex.height,TextureFormat.RGBA32,false);
texWidth = replaceTex.width; //设置图片的宽度
texHeight = replaceTex.height; //设置图片的高度
replaceTex.SetPixels(tempTex.GetPixels()); // 设置这张图片的像素
sumPixels = tempTex.GetPixels().Length; //得到这个图片的像素点数量
replaceTex.Apply();
target.texture = replaceTex; // 把刮刮乐的texture替换为我们操作的texture
}
private void Update()
{
Check();
}
/// <summary>
/// 检测进度值
/// </summary>
private void Check()
{
if (Input.GetMouseButton(0))
{
if (Camera.main != null)
{
Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit) ;
if (hit.collider != null && hit.collider.CompareTag("IsErase"))
{
float currentSchedule = Mathf.FloorToInt(fixedPixels / sumPixels * 100); //进度计算
//若进度值小于90,继续擦除
if (currentSchedule < 90)
{
ScheduleTMPText.text = "当前擦除进度:" + currentSchedule + "%";
Erase(hit.point);
}
else //提示信息更新
{
target.gameObject.SetActive(false);
TipsTMPText.text = "擦除完毕";
ScheduleTMPText.text = "当前擦除进度:100%";
}
}
}
}
}
/// <summary>
/// 实现擦除功能
/// </summary>
private void Erase(Vector3 worldPoint)
{
Vector3 localPoint = target.transform.InverseTransformPoint(worldPoint);
for (int x = (int)localPoint.x-brushSize; x <= (int)localPoint.x+brushSize; x++) //绘画范围相当于一个圆形
{
for (int y = (int)localPoint.y-brushSize; y <= (int)localPoint.y+brushSize; y++)
{
//如果这个点和鼠标此次的位置距离大于笔刷的大小,continue
if (Vector2.Distance(localPoint, new Vector2(x, y)) > brushSize)
continue;
//计算像素点的正确位置(本地坐标位置加上偏移量,本地坐标系原点在图片,但计算像素点的坐标远点在图片的左下角),修改像素点的透明度,同时要进行进度更新
int pixelX = x + texWidth / 2;
int pixelY = y + texHeight / 2;
// 如果这个点超出了图片的边界,直接continue
if (pixelX < 0 || pixelX > texWidth || pixelY < 0 || pixelY > texHeight)
continue;
Color currentColor = replaceTex.GetPixel(pixelX, pixelY);
if (currentColor.a != 0)
{
currentColor.a = 0;
replaceTex.SetPixel(pixelX,pixelY,currentColor);
fixedPixels++;
}
}
}
replaceTex.Apply();
}
}