如何将帧 * 和 * 转换从一个 UIView 传输到另一个 UIView 而不会失真



我有一个UIView,它可能应用了缩放和/或旋转转换。我的控制器创建一个新控制器并将视图传递给它。新控制器创建一个新视图,并尝试将其放置在与传递的视图相同的位置和旋转位置。它通过转换原始视图的框架来设置位置和大小:

CGRect frame = [self.view convertRect:fromView.frame fromView:fromView.superview];
ImageScrollView *isv = [[ImageScrollView alloc]initWithFrame:frame image:image];

这很好用,缩放的大小和位置完美复制。但是,如果对fromView应用了旋转变换,则不会转移。

所以我添加了这一行:

isv.transform = fromView.transform;

这很好地处理了旋转的转移,以及比例转换。结果是比例变换被有效地应用了两次,因此生成的视图太大了。

那么,如何在不加倍比例的情况下将位置(原点)、比例旋转从一个视图传输到另一个视图呢?


编辑

下面是一个更完整的代码示例,其中原始的UIImageView(fromView)用于调整UIScrollView(ImageScrollView子类)的大小和位置:

CGRect frame = [self.view convertRect:fromView.frame fromView:fromView.superview];
frame.origin.y += pagingScrollView.frame.origin.y;
ImageScrollView *isv = [[ImageScrollView alloc]initWithFrame:frame image:image];
isv.layer.anchorPoint = fromView.layer.anchorPoint;
isv.transform = fromView.transform;
isv.bounds = fromView.bounds;
isv.center = [self.view convertPoint:fromView.center fromView:fromView.superview];
[self.view insertSubview:isv belowSubview:captionView];

以下是ImageScrollView中的完整配置:

- (id)initWithFrame:(CGRect)frame image:(UIImage *)image {
    if (self = [self initWithFrame:frame]) {
        CGRect rect = CGRectMake(0, 0, frame.size.width, frame.size.height);
        imageLoaded = YES;
        imageView = [[UIImageView alloc] initWithImage:image];
        imageView.frame = rect;
        imageView.contentMode   = UIViewContentModeScaleAspectFill;
        imageView.clipsToBounds = YES;
        [self addSubview:imageView];
    }
    return self;
}

看起来转换会导致imageView放大得太大,正如你在这个丑陋的视频中看到的那样。

第一个视图的boundscentertransform复制到第二个视图。

您的代码不起作用,因为 frame 是从 boundscentertransform 派生的值frame 的 setter 尝试通过反转该过程来执行正确的操作,但是当设置非标识transform时,它并不总是正常工作。

文档在这一点上非常清楚:

如果转换属性不是标识转换,则此属性的值未定义,因此应忽略。

如果转换属性

包含非标识转换,则帧属性的值未定义,不应修改。在这种情况下,可以使用 center 属性重新定位视图,并改用 bounds 属性调整大小。

假设viewA是包含frame和transform的第一个视图,并且您希望将这些值传递给viewB。

因此,您需要获取 viewA 的原始框架并将其传递给视图 B,然后再传递转换。否则,当您添加转换时,viewB 的帧将再更改 1 次。

要获取原始帧,只需将viewA.transform转换为CGAffineTransformIdentity

这是代码

CGAffineTransform originalTransform = viewA.transform; // Remember old transform
viewA.transform = CGAffineTransformIdentity; // Remove transform so that you can get original frame
viewB.frame = viewA.frame; // Pass originalFrame into viewB
viewA.transform = originalTransform; // Restore transform into viewA
viewB.transform = originalTransform; // At this step, transform will change frame and make it the same with viewA

之后,viewA 和 viewB 将在 superView 上具有相同的 UI。

最新更新