我们继续摄像机的运用,这节我们说下游戏的截图:
照例,我们先搭好场景,在场景中创建几个物体,随意的。。。
下面我们就开始写代码:
using UnityEngine;
using System.Collections;
public class ScreenTexture : MonoBehaviour {
public int picWidth = 50; //矩形的宽度
public int picHeight = 50; //矩形的高度
public int thumbProportion = 25; //截图的显示比例
public Color borderColor = Color.white; //矩形框的颜色
public int borderWidth = 2; //矩形框的宽度
private Texture2D texture;
private Texture2D border;
private int screenWidth;
private int screenHeight;
private int frameWidth;
private int frameHeight;
private bool shoot = false;
void Start()
{
screenWidth = Screen.width;
screenHeight = Screen.height;
frameWidth = (int)(screenWidth * picWidth * 0.01f);
frameHeight = (int)(screenHeight * picHeight * 0.01f);
texture = new Texture2D(frameWidth,frameHeight,TextureFormat.RGB24,false);
border = new Texture2D(1,1,TextureFormat.ARGB32,false);
border.SetPixel(0,0,borderColor);
border.Apply();
}
void Update()
{
if (Input.GetMouseButtonUp(0))
StartCoroutine(CaptureScreen());
}
void OnGUI()
{
//绘制矩形框的四个边
GUI.DrawTexture(
new Rect(
(screenWidth*0.5f)-(frameWidth*0.5f) - borderWidth*2,
((screenHeight*0.5f)-(frameHeight*0.5f)) - borderWidth,
frameWidth + borderWidth*2,
borderWidth),
border,ScaleMode.StretchToFill);
GUI.DrawTexture(
new Rect(
(screenWidth*0.5f)-(frameWidth*0.5f) - borderWidth*2,
(screenHeight*0.5f)+(frameHeight*0.5f),
frameWidth + borderWidth*2,
borderWidth),
border,ScaleMode.StretchToFill);
GUI.DrawTexture(
new Rect(
(screenWidth*0.5f)-(frameWidth*0.5f)- borderWidth*2,
(screenHeight*0.5f)-(frameHeight*0.5f),
borderWidth,
frameHeight),
border,ScaleMode.StretchToFill);
GUI.DrawTexture(
new Rect( (screenWidth*0.5f)+(frameWidth*0.5f),
(screenHeight*0.5f)-(frameHeight*0.5f),
borderWidth,
frameHeight),
border,ScaleMode.StretchToFill);
//绘制矩形框中截取到的 Game 视图
if(shoot)
{
GUI.DrawTexture( new Rect (
10,
10,
frameWidth*thumbProportion*0.01f,
frameHeight*thumbProportion* 0.01f),
texture,ScaleMode.StretchToFill);
}
}
//截取矩形框里的 Game 视图
IEnumerator CaptureScreen () {
yield return new WaitForEndOfFrame();
texture.ReadPixels(
new Rect(
(screenWidth*0.5f)-(frameWidth*0.5f),
(screenHeight*0.5f)-(frameHeight*0.5f),
frameWidth,
frameHeight),
0,0);
texture.Apply();
shoot = true;
}
}
脚本代码中 OnGUI()函数,使用 GUI.DrawTexture()绘制了矩形框,以及矩形框中截取到的游戏视图; CaptureScreen()函数,使用 texture.ReadPixels()读取矩形框中的所有像素点,然后存储到 texture 中。触发“截图”功能的操作是,在 Game 视图中的任意位置,单击鼠标左键实现功能。
将脚本挂在Main Camera上
运行前场景:
运行后场景:(白色框内为所截取图片)
点击鼠标后:
这就成了啊!!!