2013-08-20 49 views
11

我花了很多時間試圖找到一種方法來使用CGAffineScale將視圖轉換爲給定點,包括調整錨點,移動中心轉換前後的視圖和全面的谷歌搜索。我知道這對於UIScrollview會簡單很多;但我知道在沒有人的情況下做到技術上是可行的,而且在我看來這已成爲一個分裂。如何將UIView縮放(縮放)到給定的CGPoint

This answer非常接近我想要達到的目標,但答案只給出瞭如何通過巧妙地將中心移動到與您想要的對角相對的角落來放大給定角(而不是給定點)的細節放大。

如何修改mvds' code以將UIView縮放到UIView中的任何給定點?

CGFloat s = 3; 
CGAffineTransform tr = CGAffineTransformScale(self.view.transform, s, s); 
CGFloat h = self.view.frame.size.height; 
CGFloat w = self.view.frame.size.width; 
[UIView animateWithDuration:2.5 delay:0 options:0 animations:^{ 
    self.view.transform = tr; 
    self.view.center = CGPointMake(w-w*s/2,h*s/2); 
} completion:^(BOOL finished) {}]; 

回答

4

有兩個步驟:首先放大要放大的視圖。然後,您將這個放大視圖的中心設置爲使您想要看到的部分在視圖中間結束。

你應該得出這樣在紙上和公式將遵循:(未經測試)

CGFloat s = 3; 
CGPoint p = CGPointMake(100, 200); 
CGAffineTransform tr = CGAffineTransformScale(self.view.transform, s, s); 
CGFloat h = self.view.frame.size.height; 
CGFloat w = self.view.frame.size.width; 
[UIView animateWithDuration:2.5 delay:0 options:0 animations:^{ 
    self.view.transform = tr; 
    CGFloat cx = w/2-s*(p.x-w/2); 
    CGFloat cy = h/2-s*(p.y-h/2); 
    self.view.center = CGPointMake(cx, cy); //was: (w*s/2,h-h*s/2); 
} completion:^(BOOL finished) {}]; 
+2

非常感謝您的回答。我確實嘗試過,但它仍然放大了不正確的一點。我也試着在紙上畫這個,但是邏輯沒有解決。 – glenstorey

2

我居然遇到了這個同樣的問題我自己。爲了解決這個問題,我所做的只是改變我縮放的視圖的錨點,因爲CGAffineTransforms是在視圖上執行的,與其錨點有關,所以根據錨點的位置,變換將縮放,平移或旋轉視圖不同。這裏的基本思路:

CGPoint pointToScaleTo = CGPointMake(x, y); //Just enter the coordinates you 
              //want to scale your view towards 

CGFloat viewWidth = self.view.bounds.size.width; 
CGFloat viewHeight = self.view.bounds.size.height; 

CGFloat scaleFactorX = ...; 
CGFloat scaleFactorY = ...; 

CGAffineTransform scaleTransform = CGAffineTransformMakeScale(scaleFactorX, scaleFactorY); 

[UIView animateWithDuration:2.5f delay:0.0f options:0 animations:^{ 

    //I divide the x and y coordinates by the view width and height 
    //because the anchor point coordinates are normalized to the range 
    //0.0-1.0. 
    self.view.layer.anchorPoint = CGPointMake(pointToScaleTo.x/viewWidth, pointToScaleTo.y/viewHeight); 

    //Now that the anchor point has been changed, apply the scale transform 
    self.view.layer.transform = scaleTransform; 

} completion:^(BOOL finished) {}]; 
+1

感謝您的回答。由於iOS7(我認爲),我將CGAffineTransform行更改爲'CATransform3D scaleTransform3D = CATransform3DMakeScale(scaleFactorX,scaleFactorY,1.0);''''(view.layer.transform必須是CATransform3D)。現在發生的情況是視圖跳轉,使得「pointToScaleTo」處於中心位置(這並不理想 - 理想情況下,我希望縮放到點而不是跳到,然後放大),然後旋轉-90°。我不確定我從哪裏獲得輪換。你知道如何讓它縮放到點而不是跳躍然後縮放嗎? – glenstorey

+0

您可以使用'self.view.layer.transform = CATransform3DMakeAffineTransform(scaleTransform);'將仿射變換轉換爲'CATransform3D'。 – Dennis