通过
this question and answer,我现在有了一种工作方法,可以检测任意旋转的图像何时不完全在裁剪矩形之外.
下一步是弄清楚如何正确调整它包含滚动视图缩放,以确保裁剪矩形内没有空格.为了澄清,我想放大(放大)图像;作物直肠应保持未转化.
布局层次结构如下所示:
containing UIScrollView
UIImageView (this gets arbitrarily rotated)
crop rect overlay view
… UIImageView也可以在scrollView中进行缩放和平移.
有4个手势事件需要考虑:
>平移手势(完成):通过检测它是否被错误地平移并重置contentOffset来完成.
>旋转CGAffineTransform
>滚动视图缩放
>调整裁剪矩形覆盖框架
据我所知,我应该能够使用相同的逻辑2,3和4来调整滚动视图的zoomScale,以使图像正确匹配.
如何正确计算使旋转的图像完全适合裁剪矩形所需的缩放比例?
为了更好地说明我想要完成的任务,这里是一个不正确大小的示例:
我需要计算必要的缩放比例,使它看起来像这样:
这是我到目前为止使用的Oluseyi解决方案的代码.当旋转角度很小(例如小于1弧度)时,它可以工作,但除此之外的任何东西都会变得非常糟糕.
CGRect visibleRect = [_scrollView convertRect:_scrollView.bounds toView:_imageView];
CGRect cropRect = _cropRectView.frame;
CGFloat rotationAngle = fabs(self.rotationAngle);
CGFloat a = visibleRect.size.height * sinf(rotationAngle);
CGFloat b = visibleRect.size.width * cosf(rotationAngle);
CGFloat c = visibleRect.size.height * cosf(rotationAngle);
CGFloat d = visibleRect.size.width * sinf(rotationAngle);
CGFloat zoomDiff = MAX(cropRect.size.width / (a + b),cropRect.size.height / (c + d));
CGFloat newZoomScale = (zoomDiff > 1) ? zoomDiff : 1.0 / zoomDiff;
[UIView animateWithDuration:0.2
delay:0.05
options:NO
animations:^{
[self centerToCropRect:[self convertRect:cropRect toView:self.zoomingView]];
_scrollView.zoomScale = _scrollView.zoomScale * newZoomScale;
} completion:^(BOOL finished) {
if (![self rotatedView:_imageView containsViewCompletely:_cropRectView])
{
// damn,it's still broken - this happens a lot
}
else
{
// Woo! Fixed
}
_didDetectBadRotation = NO;
}];
注意我正在使用AutoLayout,这使得框架和边界变得愚蠢.
解决方法
假设您的图像矩形(图中的蓝色)和裁剪矩形(红色)具有相同的纵横比和中心.旋转时,图像矩形现在有一个边界矩形(绿色),这是您希望裁剪缩放到的(有效地,通过缩小图像).
要有效扩展,您需要知道新边界矩形的尺寸,并使用适合裁剪矩形的比例因子.边界矩形的尺寸相当明显
(a + b) x (c + d)
请注意,每个段a,b,c,d是由边界矩形和旋转图像rect形成的直角三角形的相邻或相对侧.
a = image_rect_height * sin(rotation_angle) b = image_rect_width * cos(rotation_angle) c = image_rect_width * sin(rotation_angle) d = image_rect_height * cos(rotation_angle)
您的比例因子很简单
MAX(crop_rect_width / (a + b),crop_rect_height / (c + d))
这是一个参考图: