2012-04-18 62 views
0

我有一个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过大,正如您在this ugly video中看到的那样。

回答

6

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

您的代码不起作用,因为frame是从的boundscentertransform衍生的值。 frame的设置程序通过反转进程来尝试做正确的事情,但在设置非身份transform时,它不能始终正常工作。

documentation在这一点上很清楚:

如果变换属性不是恒等变换,这个属性的值是不确定的,因此应被忽略。

...

如果变换属性包含非恒等变换,框架属性的值是未定义的,并且不应当被修改。在这种情况下,您可以使用center属性重新定位视图,并使用bounds属性调整大小。

+0

Hrm,是的,那*几乎*让我在那里。现在,新观点的起源并不完全正确。 – theory 2012-04-18 07:27:33

+0

我没有设置“中心”,我得到了原点。但是新形象的规模仍然是错误的。无论我做什么,它的规模都过大。即使我没有应用比例变换,新视图中的图像仍然稍大。这让我疯狂。 – theory 2012-04-19 06:53:44

+0

真的很难说你的问题可能没有看到一些代码。这是否发生在一个普通的UIView?你是否将旧视图中的所有其他属性复制到新视图(包括任何子视图)? – 2012-04-19 16:24:06

2

让我们说viewA是第一个视图,其中包含框架&变换,并且您希望将这些值传递给viewB。

因此,您需要获取原始的viewA帧,并在通过变换之前将其传递给viewB。否则,当您添加变换时,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将对上海华相同的用户界面。

相关问题