Unity-微信截图功能简单复刻-04修改纹理
思路
创建全屏大小纹理,类型为TextureFormat.RGBA32。
创建纹理数组,大小为屏幕大小的4倍。
修改纹理数组数据,纹理应用修改后的数据。
示例
using UnityEngine;
using UnityEngine.UI;
public class TestTextureChange : MonoBehaviour
{[SerializeField] RawImage image;Texture2D texture;byte[] textureData;private void Awake(){texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGBA32, false);texture.filterMode = FilterMode.Point;texture.wrapMode = TextureWrapMode.Clamp;image.texture = texture;textureData = new byte[Screen.width * Screen.height * 4];texture.LoadRawTextureData(textureData);texture.Apply(false);}private void Update(){if (Input.GetMouseButtonDown(0)){ var xLength = Random.Range(0, Screen.width);var yLength = Random.Range(0, Screen.height);Color color = Color.white;color.r = Random.Range(0f, 1f);color.g = Random.Range(0f, 1f);color.b = Random.Range(0f, 1f);FillColor(xLength, yLength, color);}if (Input.GetMouseButtonUp(0))FillColor(Screen.width, Screen.height, Color.clear);}void FillColor(int x, int y, Color32 color){for (int i = 0; i < x; i++){for (int j = 0; j < y; j++)SetPixelColor(i, j, color);}texture.LoadRawTextureData(textureData);texture.Apply(false);}void SetPixelColor(int x, int y, Color32 color){if (x < 0 || y < 0 || x >= texture.width || y >= texture.height){return;}else{int index = (texture.width * y + x) * 4;textureData[index++] = color.r;textureData[index++] = color.g;textureData[index++] = color.b;textureData[index] = color.a;}}
}
层级结构
运行结果
按下鼠标左键,显示一个纯色矩形。
松开鼠标左键,清除纯色矩形。
知识
TextureFormat.RGBA32
橡皮檫制作思路
使用透明颜色,修改纹理数组。