在游戏中经常会将游戏画面的截屏分享给好友,利用各平台所提供的SDK可以完美的实现分享功能,不过要截屏游戏画面,还是需要自己敲两行代码才行~
用一个截屏专用的相机,先设置好相机的参数(Size,TargetTexture等 ···),将需要截屏的画面调整到相机前,调整好位置和大小,若截屏尺寸有多个,可以动态设置相机的参数,还有一点,记得设置相机的Culling Mask~
然后,上代码 ~ 三五行搞定
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScreenshotManager : MonoBehaviour
{
[SerializeField] Camera screenshotCamera;
[SerializeField] RawImage screenshotImage;
public void Awake()
{
//Test
StartCoroutine(Screenshot());
}
public IEnumerator Screenshot()
{
screenshotCamera.gameObject.SetActive(true);
yield return new WaitForEndOfFrame();
//screenshotImage.texture = ScreenshotByScreenSize();
screenshotImage.texture = ScreenshotByRenderTexture(screenshotCamera.targetTexture);
yield return new WaitForEndOfFrame();
screenshotCamera.gameObject.SetActive(false);
}
//截取屏幕,返回Texture2D
public Texture2D ScreenshotByScreenSize()
{
//创建Texture2D(尺寸设置为屏幕大小)
Texture2D screenshotTex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false);
//绘制一个矩形,设置顶点,长宽(尺寸设置为屏幕大小)
Rect screenshotRect = new Rect(0, 0, Screen.width, Screen.height);
//读取屏幕的局部像素信息保存在贴图中
screenshotTex.ReadPixels(screenshotRect, 0, 0);
screenshotTex.Apply();
//返回值
return screenshotTex;
}
//根据相机RenderTexture尺寸,截取屏幕,返回Texture2D
public Texture2D ScreenshotByRenderTexture(RenderTexture renderTexture)
{
//RenderTexture接收渲染相机结果
RenderTexture activerRender = renderTexture;
RenderTexture.active = activerRender;
//创建Texture2D,绘制矩形(尺寸为给定RenderTexture大小)
Texture2D screenshotTex = new Texture2D(activerRender.width, activerRender.height);
Rect screenshotRect = new Rect(0, 0, activerRender.width, activerRender.height);
//获取Texture2D数据
screenshotTex.ReadPixels(screenshotRect, 0, 0);
screenshotTex.Apply();
//
return screenshotTex;
}
}