Unity使用RenderTexture进行截屏(海报截图分享、适配各种尺寸比例的屏幕)
发布日期:2021-06-30 19:38:16
浏览次数:3
分类:技术文章
本文共 1975 字,大约阅读时间需要 6 分钟。
Unity截屏分享功能,需要实现截屏功能。
美术那边会出一张海报图,尺寸为1280x720,包装成预设,预设上还有叠加一些其他UI,比如头像、昵称、二维码、宣传语、logo等等。
如果把海报图铺满全屏,那么如果手机屏幕宽高比不是1280:720,那么海报图就会被拉伸变形,如果等比例缩放海报图,那海报图就会有部分超出屏幕外,无法被截屏到。
解决办法:
海报图示例化后不缩放不拉伸,如果是在1280:720的宽高比的手机上,就刚好铺满全屏,如果是其他宽高比的屏幕,则海报图四周有可能会有留空,没有铺满全屏。没关系,截屏的时候,只读取海报图所在的像素位置即可,这里需要进行一些换算,具体看下面代码的region 2的部分的逻辑
public void cutScreen(){ RenderTexture rt = new RenderTexture(Screen.width, Screen.height, 24); // 赋值各个摄像机的targetTexture,注意摄像机的渲染顺序 // m_mainCam、m_auxCam、m_nguiCam是我这边定义的三个摄像机 m_mainCam.targetTexture = rt; m_mainCam.Render(); m_auxCam.targetTexture = rt; m_auxCam.Render(); m_nguiCam.targetTexture = rt; m_nguiCam.Render(); RenderTexture.active = rt; #region 1 // 全屏读取像素 //Texture2D tex = new Texture2D(Screen.width, Screen.height, TextureFormat.RGB24, false); //tex.ReadPixels(new Rect(0,0,Screen.width,Screen.height),0,0); #endretion 1 #region 2 // 读取1280x720宽高比的像素,适用于1280x720宽高比的海报截屏分享 float factor_x = Screen.width * 1.0f / Screen.height/ (1280 * 1.0f / 720); factor_x = factor_x < 1.0f ? 1.0f : factor_x; float factor_y = 1280 * 1.0f / 720 / (Screen.width * 1.0f / Screen.height); factor_y = factor_y < 1.0f ? 1.0f : factor_y; Texture2D tex = new Texture2D((int)(width / factor_x), (int)(height / factor_y), TextureFormat.RGB24, false); tex.ReadPixels(new Rect((width - width / factor_x) / 2, (height - height / factor_y) / 2f, width / factor_x, height / factor_y), 0, 0); #endregion 2 tex.Apply(); RenderTexture.active = null; m_mainCam.targetTexture = null; m_auxCam.targetTexture = null; m_nguiCam.targetTexture = null; Destroy(rt); GameObject photo = new GameObject("photo"); UITexture uiTex = photo.AddComponent(); uiTex .mainTexture = tex; photo.transform.parent = m_gamePanel.transform; photo.transform.localPosition = new Vector3(); photo.transform.localScale = Vector3.one; uiTex.width = 611; uiTex.height = 344;}
转载地址:https://linxinfa.blog.csdn.net/article/details/49493775 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
表示我来过!
[***.240.166.169]2024年04月10日 21时42分16秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
最全的UIAlertController的使用
2019-04-30
CBPeripheralManager学习笔记
2019-04-30
CLLocationManager定位服务
2019-04-30
iOS 开发如何获取当前的应用版本号
2019-04-30
友盟统计的那些事
2019-04-30
3款流行的移动应用平台数据统计比较
2019-04-30
iOS 开发 实现 将16进制字符串转换成16进制数
2019-04-30
UILabel自适应高度和自动换行
2019-04-30
NSTimer的使用方法 --初始化、暂停、继续
2019-04-30
iOS开发支付宝 集成SDK注意事项
2019-04-30
UIApplicationDelegate中几个常用的回调方法
2019-04-30
iOS开发遇到的问题
2019-04-30
UISegmentedControl的详细使用
2019-04-30
iOS 使用贝塞尔曲线,报错说是上下文错误
2019-04-30
iOS 开发贝塞尔曲线
2019-04-30
SQL
2019-04-30
html之动态添加控件实现轮播
2019-04-30
三种方法使用jquery获取验证码倒计时,并设置防重复点击
2019-04-30