Unity 截图

本文介绍了在Unity中如何使用官方API进行全屏截图以及指定尺寸截图的方法。通过示例代码展示了如何利用Rect定义截图区域,并使用ReadPixels读取屏幕像素,最后将截图保存为PNG格式。示例涵盖了屏幕的四个象限和中心区域的截图操作。
摘要由CSDN通过智能技术生成

方法1

不能指定截图尺寸
官方API
ScreenCapture.CaptureScreenshot(Application.dataPath + “/Resources/1.png”); //指定路径和后缀名 jpg或者png

方法2

指定截图尺寸
注意:矩形局域不能超过当前画面显示尺寸
Rect 确定截取区域的大小
ReadPixels 将屏幕像素读取到纹理中 参数1 矩形区域的左下角为原点 因此可以修改矩形的中心点 调整截图位置 参数2 参数3 将截图进行偏移
EncodeToPNG 纹理编码为 PNG 格式
File.WriteAllBytes 创建一个新文件,在其中写入指定的字节数组,然后关闭该文件。 如果目标文件已存在,则覆盖该文件

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Photo : MonoBehaviour
{
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Rect rec = new Rect(0, 0, Screen.width / 2, Screen.height / 2);

            rec.center = new Vector2(Screen.width / 4, Screen.height / 4 * 3);//屏幕一分为四 左上侧部分
            StartCoroutine(IBegin(rec, Application.dataPath + "/Resources/A.Png"));

            rec.center = new Vector2(Screen.width / 4 * 3, Screen.height / 4 * 3);//屏幕一分为四 右上侧部分
            StartCoroutine(IBegin(rec, Application.dataPath + "/Resources/B.Png"));

            rec.center = new Vector2(Screen.width / 4, Screen.height / 4);//屏幕一分为四 左下侧部分
            StartCoroutine(IBegin(rec, Application.dataPath + "/Resources/C.Png"));

            rec.center = new Vector2(Screen.width / 4 * 3, Screen.height / 4);//屏幕一分为四 右下侧部分
            StartCoroutine(IBegin(rec, Application.dataPath + "/Resources/D.Png"));
            
            rec.center = new Vector2(Screen.width / 2, Screen.height / 2);//屏幕中心区域
            StartCoroutine(IBegin(rec, Application.dataPath + "/Resources/E.Png"));

            rec = new Rect(0,0,Screen.width,Screen.height);
            StartCoroutine(IBegin(rec, Application.dataPath + "/Resources/F.Png"));//整体
        }
    }
    IEnumerator IBegin(Rect rect, string url)
    {
        yield return new WaitForEndOfFrame();
        CaptureScreenshot(rect, url);
    }
    private void CaptureScreenshot(Rect rect, string url)
    {
        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);

        screenShot.ReadPixels(rect, 0, 0);
        screenShot.Apply();
        byte[] bytes = screenShot.EncodeToPNG();

        System.IO.File.WriteAllBytes(url, bytes);
    }
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值