您当前的位置: 首页 >  unity
  • 7浏览

    0关注

    193博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Unity截图功能并使用UI显示

我寄人间雪满头丶 发布时间:2022-07-15 15:11:34 ,浏览量:7

前言

最近在做一个房间装修项目,有一个功能需要对比装修前后的效果,经过考虑决定使用截图功能制作。 代码:

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

public class ScreenShot : MonoBehaviour
{
    public Image img; //显示的UI
    private Texture2D texture;
    private int w;
    private int h;
    void Start()
    {
    	//获取屏幕尺寸
        w = Screen.width;
        h = Screen.height;
        texture= new Texture2D(w, h);
    }
    void Update()
    {
	    //按P截图,测试用
        if (Input.GetKeyDown(KeyCode.P))
        {
            StartCoroutine(SaveImage());
        }
    }

    IEnumerator SaveImage()
    {
        yield return new WaitForEndOfFrame();
        Rect rect = new Rect(0, 0, w, h);
        texture.ReadPixels(rect, 0, 0, true); //截图
        texture.Apply();
        Sprite sp = Sprite.Create(texture, rect, Vector2.zero); //Texture2D转换为Sprite
        img.sprite = sp;
        Debug.Log("write a pic");
        yield return null;
    }
}
效果

在这里插入图片描述 在这里插入图片描述

备注

需求是截全屏,使用的Image布局拉满全屏。注意截图时要屏蔽UI。(具体根据需求) 这里是缓存到内存中,如果需要保存可以使用文件流操作。

        byte[] bytes = texture.EncodeToPNG();
        File.WriteAllBytes(Application.streamingAssetsPath + "/" + "name" + ".png", bytes);
关注
打赏
1648518768
查看更多评论
立即登录/注册

微信扫码登录

0.1817s