Unity实现截图功能
程序员文章站
2022-06-13 17:27:33
本文实例为大家分享了unity实现截图功能的具体代码,供大家参考,具体内容如下一、使用unity自带apiusing unityengine;using unityengine.ui; public...
本文实例为大家分享了unity实现截图功能的具体代码,供大家参考,具体内容如下
一、使用unity自带api
using unityengine; using unityengine.ui; public class screenshottest : monobehaviour { public rawimage img; private void update() { //使用screencapture.capturescreenshot if (input.getkeydown(keycode.a)) { screencapture.capturescreenshot(application.datapath + "/resources/screenshot.jpg"); img.texture = resources.load<texture>("screenshot"); } //使用screencapture.capturescreenshotastexture if (input.getkeydown(keycode.s)) { img.texture = screencapture.capturescreenshotastexture(0); } //使用screencapture.capturescreenshotastexture if (input.getkeydown(keycode.d)) { rendertexture rendertexture = new rendertexture(720, 1280, 0); screencapture.capturescreenshotintorendertexture(rendertexture); img.texture = rendertexture; } } }
经过测试,使用screencapture.capturescreenshotastexture和screencapture.capturescreenshotastexture截取的都是整个屏幕,相当于手机的截屏,无法自定义截图区域,作用不大。使用screencapture.capturescreenshot会有延迟。
二、通过texture2d.readpixels来读取屏幕区域像素
using unityengine; using system.collections; using system; public class screenshottest : monobehaviour { private void update() { if (input.getkeydown(keycode.a)) { startcoroutine(capturebyrect()); } } private ienumerator capturebyrect() { //等待渲染线程结束 yield return new waitforendofframe(); //初始化texture2d, 大小可以根据需求更改 texture2d mtexture = new texture2d(screen.width, screen.height, textureformat.rgb24, false); //读取屏幕像素信息并存储为纹理数据 mtexture.readpixels(new rect(0, 0, screen.width, screen.height), 0, 0); //应用 mtexture.apply(); //将图片信息编码为字节信息 byte[] bytes = mtexture.encodetopng(); //保存(不能保存为png格式) string filename = datetime.now.hour + ":" + datetime.now.minute + ":" + datetime.now.second + ".jpg"; system.io.file.writeallbytes(application.streamingassetspath + "/screenshot/" + filename, bytes); unityeditor.assetdatabase.refresh(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。