2012-04-18 21 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將對上海華相同的用戶界面。

相關問題