Unity摄像机的使用三:游戏的截图

我们继续摄像机的运用,这节我们说下游戏的截图:

照例,我们先搭好场景,在场景中创建几个物体,随意的。。。


下面我们就开始写代码:

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上


然后就是运行游戏了啊:

运行前场景:


运行后场景:(白色框内为所截取图片)


点击鼠标后:


这就成了啊!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值