unity中实现截取全屏的功能
1、截屏方法如下:
/// <summary>
/// 读取指定相机渲染的像素---本次使用的
/// </summary>
private void ScreenShot_ReadPixelsWithCamera(Camera _camera)
{
//对指定相机进行 RenderTexture
RenderTexture renTex = new RenderTexture(Screen.width, Screen.height, 16);
_camera.targetTexture = renTex;
_camera.Render();
RenderTexture.active = renTex;
//读取像素,这句比较重要,如果不加TextureFormat.RGB24,截出来的图片就是很模糊的,里边很多像素点,需要多加注意
Texture2D tex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
//读取图片像素
tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
tex.Apply();
//压缩图片的功能---可以不需要
tex = ScaleTexture(tex, tex.width / 3, tex.height / 3);
PictureList.Add(tex);//这一步是我需要,存储了一下截屏的图片,可以省去
MyRectTransform.GetComponent<Image>().sprite = ToSprite(tex);
//读取目标相机像素结束,渲染恢复原先的方式
_camera.targetTexture = null;
RenderTexture.active = null;
Destroy(renTex);
}
2、 将texture转换为sprite
/// <summary>
/// 将texture转换为sprite
/// </summary>
/// <param name="self"></param>
/// <returns></returns>
public Sprite ToSprite(Texture2D self)
{
var rect = new Rect(0, 0, self.width, self.height);
var pivot = Vector2.one * 0.5f;
var newSprite = Sprite.Create(self, rect, pivot);
return newSprite;
}
3、压缩图片的功能:
public Texture2D ScaleTexture(Texture2D source, int targetWidth, int targetHeight)
{
Texture2D result = new Texture2D(targetWidth, targetHeight, source.format, true);
Color[] rpixels = result.GetPixels(0);
float incX = ((float)1 / source.width) * ((float)source.width / targetWidth);
float incY = ((float)1 / source.height) * ((float)source.height / targetHeight);
for (int px = 0; px < rpixels.Length; px++)
{
rpixels[px] = source.GetPixelBilinear(incX * ((float)px % targetWidth), incY * ((float)Mathf.Floor(px / targetWidth)));
}
result.SetPixels(rpixels, 0);
result.Apply();
return result;
}
4、调用截屏方法即可:
private void JiepingButtonClick()
{
ScreenShot_ReadPixelsWithCamera(Camera.main);
}