Crop rectangle does not fit within image data.之getFramingRect计算不合理
今日部分手机运行时候发生如下异常:
FATAL EXCEPTION: Thread-6
Process: yourPackageName, PID: 25220
java.lang.IllegalArgumentException: Crop rectangle does not fit within image data.
at com.camerascan.demo.Scan.camera.PlanarYUVLuminanceSource.<init>(PlanarYUVLuminanceSource.java:51)
at com.camerascan.demo.Scan.camera.CameraManager.buildLuminanceSource(CameraManager.java:458)
相应的代码:
if (left + width > dataWidth || top + height > dataHeight)
{
throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
}
一番排查
left大概就是CameraManager的getFramingRect()中的framingRect的left
width 大概就是CameraManager的getFramingRect()中的framingRect的width
dataWidth 就是screenResolution.x
所以关键点就在CameraManager的getFramingRect()中有一段扫码框尺寸的计算
int height = screenResolution.y / 2;
width = height;
int leftOffset = (screenResolution.x - width) / 2;
int topOffset = (screenResolution.y - height) / 2 - 80;
framingRect = new Rect(leftOffset, topOffset, screenResolution.x - leftOffset, topOffset + height);
抛出异常是在 if (left + width > dataWidth || top + height > dataHeight)
的情况,反之在运行正常情况下,(left + width <= dataWidth || top + height <= dataHeight)
, 也就是width <=screenResolution.x
,就是扫码框尺寸小于等于屏幕宽度,发生异常就是 width >screenResolution.x
超出屏幕尺寸范围,因为 width = height
,int height = screenResolution.y / 2;
倒推一把就是screenResolution.y /screenResolution.x > 2
的情况,这种情况在什么样手机会出现呢,y是x的2倍以上,就是屏幕很瘦长喽,你猜对了,就是最近新出的全面屏,看看出现问题手机的分辨率比例就验证了我们的推测:OPPO R17(2340x1080像素)、荣耀V20(2310x1080像素)、VIVO Y85(2280x1080像素)等。
问题症结找到了:int height = screenResolution.y / 2;
这个方法太粗暴,在分辨率 Y/X > 2
时候会发生异常,没有充分考虑屏幕尺寸情况,所以解决办法很简单,既然Y轴不可靠,就用X轴,修改如下:
int height = screenResolution.y / 2;
float percentage = (float) screenResolution.y / (float) screenResolution.x;
if (percentage > 2)
{
//解决percentage>2 ,width超出屏幕,抛出异常("Crop rectangle does not fit within image data.");
height = screenResolution.x * 4 / 5;
}
width = height;
int leftOffset = (screenResolution.x - width) / 2;
int topOffset = (screenResolution.y - height) / 2 - 80;
framingRect = new Rect(leftOffset, topOffset, screenResolution.x - leftOffset, topOffset + height);
最后验证,完美解决,如果有用请点赞哦,如果有分析不到位或者更好的方案,欢迎各位留言探讨