gpt4 book ai didi

ios - 缩放 ScrollView 内的旋转图像以适合(填充)覆盖矩形的框架

转载 作者:可可西里 更新时间:2023-11-01 03:39:11 25 4
gpt4 key购买 nike

通过this question and answer我现在有了一种有效的方法来检测任意旋转的图像何时没有完全超出裁剪矩形。

下一步是弄清楚如何正确调整它包含 ScrollView 缩放以确保裁剪矩形内没有空白区域。澄清一下,我想放大(放大)图像;裁剪矩形应保持未转换状态。

布局层次结构如下所示:

containing UIScrollView
UIImageView (this gets arbitrarily rotated)
crop rect overlay view

... UIImageView 也可以在 scrollView 内缩放和平移。

有 4 个手势事件需要考虑:

  1. 平移手势(完成):通过检测平移是否不正确并重置 contentOffset 来完成。
  2. 旋转CGAffineTransform
  3. ScrollView 缩放
  4. 裁剪矩形叠加框的调整

据我所知,我应该能够对 2、3 和 4 使用相同的逻辑来调整 ScrollView 的 zoomScale 以使图像适合。

如何正确计算使旋转图像完美适合裁剪矩形所需的缩放比例?

为了更好地说明我要完成的工作,这里有一个不正确大小的示例:

enter image description here

我需要计算使它看起来像这样所需的缩放比例:

enter image description here

这是我目前使用下面的 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 都是由边界矩形和旋转后的图像矩形形成的直角三角形的相邻边或对边。

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))

这是一个引用图:

enter image description here

关于ios - 缩放 ScrollView 内的旋转图像以适合(填充)覆盖矩形的框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26824513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com