关于unity区域截图像素越界解决办法

首先说一下区域截图,先上代码,简单易懂。
Texture2D shot = new Texture2D((int)(rect.rect.width ), (int)(rect.rect.height));
float x = rect.localPosition.x + (Screen.width - rect.rect.width ) * 0.5f;
float y = rect.localPosition.y + (Screen.height - rect.rect.height ) * 0.5f;

    Rect position = new Rect(x, y, rect.rect.width, rect.rect.height);
    shot.ReadPixels(position, 0, 0);
    shot.Apply();

rect为你要截图的图片rect,x和y为图片左下角的坐标点,然后去读像素点保存成图片,读取像素点中的position为你的区域,其实此时的区域为你从rect的图片区域。这是区域截图的代码。
但是此代码有个问题。就是当你做好适配后,调整屏幕分辨率后你的截图就发生问题,比如当1200600的时候,截图就不是正好你的rect的位置了,我的默认分辨率是19201080,而最可恶的是当屏幕分辨率小于你的rect的whith和height的时候,就会报错了,大家应该会出现过这个错误,就是你的屏幕没那么大然后还读那么多像素点,结果就是没那么多点让你去读然后去写成图片。
所以你需要一个比例,保证你的rect在屏幕改变分辨率的时候依然截取到你想要的rect的区域。
其实这个有点坑人,你的canvas必须要设置一个默认的分辨率,以这个为基准的,我就是1920*1080为例子,canvas设置好后,在原来的代码上加以修改。贴上代码:
float ratio_x = Screen.width / 1920f;
//float ratio_y = Screen.height / 1080f;
Texture2D shot = new Texture2D((int)(rect.rect.width * ratio_x), (int)(rect.rect.height * ratio_x));
float x = rect.localPosition.x + (Screen.width - rect.rect.width * ratio_x) * 0.5f;
float y = rect.localPosition.y + (Screen.height - rect.rect.height * ratio_x) * 0.5f;

    Rect position = new Rect(x, y, rect.rect.width * ratio_x, rect.rect.height * ratio_x);
    shot.ReadPixels(position, 0, 0);
    shot.Apply();

这里我解释一下,ratio_x为我以宽设置的比例,就是当我屏幕不为这个1920的时候我看看我这个比例是多少。那么new 的tex就必须也得改版。不然我apply的时候其实像素点根本不够的,其实你看你的rect的with和height的时候,他依然是以前的值,比如500,你改变一下分辨率看看,你会发现ui的width和height都不改变,改变的scale。
不管scale改变多少,你只需要知道现在的分辨率和我1920为基准的差多少而已。
差多少我就乘以多少这个比例就完事了。
所以你取区域截图的x和y 都要乘以这个比例。 最终不管你怎么改变还是你想要的区域截图。
这个shot你直接拿到你要显示的地方就可以了。
最终代码做一下优化:

float ratio_x = Screen.width / 1920f;
//float ratio_y = Screen.height / 1080f;
float width = rect.rect.width * ratio_x;
float height = rect.rect.height * ratio_x;
Texture2D shot = new Texture2D((int)width, (int)height);
float x = rect.localPosition.x + (Screen.width - width) * 0.5f;
float y = rect.localPosition.y + (Screen.height - height) * 0.5f;

    Rect position = new Rect(x, y, width, height);
    shot.ReadPixels(position, 0, 0);
    shot.Apply();
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值