using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Windows;
/**
*
* Unity指定区域截图
* Create by Camming 2020/06/13
*
*/
public class Screen : MonoBehaviour
{
public Transform test;
// Start is called before the first frame update
void Start()
{
string fileName =Application.persistentDataPath+"/tfw"+"/userPic.png";
if (!Directory.Exists(Application.persistentDataPath+"/tfw"))
{
Debug.LogError("Start 目录不存在 创建");
Directory.CreateDirectory(Application.persistentDataPath+"/tfw");
}
IEnumerator screenCapture = CaptureByUI(test.GetComponent<RectTransform>(), fileName);
StartCoroutine(screenCapture);
}
// Update is called once per frame
void Update()
{
}
/// <summary>
/// 1、获取纹理
/// 2、计算开始坐标和长宽
/// 3、读取像素
/// 4、应用读取
/// 5、将纹理转为图片byte数组
/// 6、将图片byte数据内容写入到新创建的文件中
/// </summary>
/// <param name="UIRect"></param>
/// <param name="mFileName"></param>
/// <returns></returns>
public IEnumerator CaptureByUI(RectTransform UIRect, string mFileName)
{
//等待帧画面渲染结束
yield return new WaitForEndOfFrame();
int width = (int)(UIRect.rect.width );
int height = (int)(UIRect.rect.height);
Texture2D screenTure = new Texture2D(width, height, TextureFormat.RGB24, false);
//左下角为原点(0, 0)
float leftBtmX = UIRect.transform.position.x + UIRect.rect.xMin ;
float leftBtmY = UIRect.transform.position.y + UIRect.rect.yMin ;
//从屏幕读取像素, leftBtmX/leftBtnY 是读取的初始位置,width、height是读取像素的宽度和高度
screenTure.ReadPixels(new Rect(leftBtmX, leftBtmY, width, height), 0, 0);
//执行读取操作
screenTure.Apply();
byte[] bytes = screenTure.EncodeToPNG();
if (Directory.Exists(mFileName))
{
Debug.LogError("将旧的图片删除");
Directory.Delete(mFileName);
}
//保存
System.IO.File.WriteAllBytes(mFileName, bytes);
}
}
Unity 指定区域截屏2020-06-13
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。