Unity-微信截图功能简单复刻-02屏幕采样
思路
采样相机画面,更新到纹理,使用RawImage组件显示纹理
示例脚本
using UnityEngine;
using UnityEngine.UI;
public class TestScreenSample : MonoBehaviour
{[SerializeField] RawImage contentShow;//采样内容显示到图片组件上[SerializeField] Camera drawCamera;//采样相机Texture2D texture;//纹理private void Awake(){//创建一个纹理texture = new Texture2D(Screen.width, Screen.height, TextureFormat.RGBA32, false);texture.filterMode = FilterMode.Point;texture.wrapMode = TextureWrapMode.Clamp;contentShow.texture = texture;//使用空白纹理信息填充byte[] blankTextureData = new byte[Screen.width * Screen.height * 4];texture.LoadRawTextureData(blankTextureData);texture.Apply(false);}private void Update(){//按下空格键进行屏幕采样 更新纹理if (Input.GetKeyDown(KeyCode.Space))Sampling(ref texture, drawCamera, texture.width, texture.height);}void Sampling(ref Texture2D texture, Camera drawCamera, int width, int height){//创建临时RenderTextureRenderTexture RT = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default, 1);//相机画面渲染到RenderTexturevar targetTexture = drawCamera.targetTexture;drawCamera.targetTexture = RT;drawCamera.Render();drawCamera.targetTexture = targetTexture;//读取RenderTexture的像素数据到texturevar activeTexture = RenderTexture.active;RenderTexture.active = RT;texture.ReadPixels(new Rect(0, 0, width, height), 0, 0);texture.Apply(false);RenderTexture.active = activeTexture;RenderTexture.ReleaseTemporary(RT);}
}
场景结构
Canvas渲染模式为Overlay,
TestScreenSample对象添加测试脚本,设置引用对象。
运行画面
运行,按下空格键,左上角显示采样内容。
移动立方体,按下空格键,采样内容变化。
技术组合
Texture2D
Camera
RenderTexture