unity中实现截屏的方法

该代码段展示了在Unity3D中如何创建一个Texture2D对象,读取屏幕指定区域的像素信息,将其转化为纹理,然后编码为PNG图像并保存到本地。主要方法包括创建空纹理、读取像素、应用更改和编码为图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先创建一个的空纹理,大小可根据实现需要设置。Texture2D texture2D = new Texture2D(int width, int height);
将相应的像素信息存储入这个新建的空纹理中。texture2D.ReadPixels或texture2D.SetPixels
最后,将所有像素信息,“申请”成正式的Texture2D类对象。texture2D.Apply();
 

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

public class jieping : MonoBehaviour
{


    // Start is called before the first frame update
    void Start()
    {
       
    }

    // Update is called once per frame
    void Update()
    {
        
    }
  public  void jp_button()
    {
        // 创建一个 Rect 对象
        Rect rect = new Rect(0, 0, Screen.width, Screen.height);

        // 调用 CaptureScreenshot2 方法,并将返回的 Texture2D 对象赋给一个变量
        Texture2D screen = CaptureScreenshot2(rect);


    }
    /// <summary>
    /// Captures the screenshot2.
    /// </summary>
    /// <returns>The screenshot2.</returns>
    /// <param name="rect">Rect.截图的区域,左下角为o点</param>
    Texture2D CaptureScreenshot2(Rect rect)
    {
        Texture2D screenShot = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);//先创建一个的空纹理,大小可根据实现需要来设置
        screenShot.ReadPixels(rect, 0, 0);//读取屏幕像素信息并存储为纹理数据,
        screenShot.Apply();
        byte[] bytes = screenShot.EncodeToPNG();//然后将这些纹理数据,成一个png图片文件

        string filename = Application.dataPath + "/Screenshot.png";
        System.IO.File.WriteAllBytes(filename, bytes);
        Debug.Log(string.Format("截屏了一张图片: {0}", filename));
        //最后,我返回这个Texture2d对象,这样我们直接,所这个截图图示在游戏中,当然这个根据自己的需求的。
        return screenShot;
    }

}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值