2013-05-06 18 views
1

我已經創建了UIView的mainView objcet,並在其上添加了一個子視圖。我在mainView上應用了變換來減小幀大小。但mainView的subview框架並未減少。如何減小這個子視圖的大小。如何在mainView上應用轉換後獲取子視圖的框架?

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 
    CGFloat widthM=1200.0; 
    CGFloat heightM=1800.0; 
    UIView *mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, widthM, heightM)]; 
    mainView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"te.png"]]; 
    [self.view addSubview:mainView]; 
    CGFloat yourDesiredWidth = 250.0; 
    CGFloat yourDesiredHeight = yourDesiredWidth *heightM/widthM; 
    CGAffineTransform scalingTransform; 
    scalingTransform = CGAffineTransformMakeScale(yourDesiredWidth/mainView.frame.size.width, yourDesiredHeight/mainView.frame.size.height); 
    mainView.transform = scalingTransform; 
    mainView.center = self.view.center; 
    NSLog(@"mainView:%@",mainView); 
    UIView *subMainView= [[UIView alloc] initWithFrame:CGRectMake(100, 100, 1000, 1200)]; 
    subMainView.backgroundColor = [UIColor redColor]; 
    [mainView addSubview:subMainView]; 
    NSLog(@"subMainView:%@",subMainView); 

} 

的NSLog的這些觀點:

mainView:<UIView: 0x8878490; frame = (35 62.5; 250 375); transform = [0.208333, 0, 0, 0.208333, 0, 0]; layer = <CALayer: 0x8879140>> 
subMainView:<UIView: 0x887b8c0; frame = (100 100; 1000 1200); layer = <CALayer: 0x887c160>> 

這裏MAINVIEW的寬度爲250,子視圖的寬度是1000,但是當我得到模擬器的輸出,子視圖正確佔領,但它的不能跨越mainView。怎麼可能?轉換後如何獲得相對於mainView框架的子視圖框架?

回答

7

你看到的是預期的行爲。 UIView的框架與其父項相關,所以在將轉換應用於其超級視圖時它不會更改。雖然該視圖也會出現「扭曲」,但該框架不會反映這些更改,因爲它仍處於與其父項相同的位置。
但是,我認爲你想獲得相對於最頂層UIView的視圖框架。在這種情況下的UIKit提供以下功能:

  • – [UIView convertPoint:toView:]
  • – [UIView convertPoint:fromView:]
  • – [UIView convertRect:toView:]
  • – [UIView convertRect:fromView:]

我這些應用到你的例子:

CGRect frame = [[self view] convertRect:[subMainView frame] fromView:mainView]; 
NSLog(@"subMainView:%@", NSStringFromCGRect(frame)); 

這是輸出:

subMainView:{{55.8333, 83.3333}, {208.333, 250}} 
2

除了s1m0n答案,有關應用變換矩陣視圖,美麗的事情是,你可以保持推理在原座標系而言(在你的情況,您可以使用未轉換的座標系處理subMainView,這就是爲什麼即使subMainView的框架大於mainView的轉換框架,它仍然不會跨越父視圖,因爲它會自動轉換)。這意味着當你有一個變換後的父視圖(例如旋轉和縮放),並且你想在相對於這個父視圖的特定點上添加一個子視圖時,你不必先跟蹤以前的變換,以便這樣做。

如果你真的有興趣知道的子視圖的框架在進行轉化座標系統,這將是足以相同的變換應用到子視圖的矩形:

CGRect transformedFrame = CGRectApplyAffineTransform(subMainView.frame, mainView.transform); 

如果隨後的NSLog這CGRect,你將獲得:

Transformed frame: {{20.8333, 20.8333}, {208.333, 250}} 

我相信這是,是,你正在尋找的值。我希望這回答了你的問題!

+0

它不適用於iOS 8 – 2015-07-20 20:26:11

+1

在回答這個問題的時候,iOS 7幾乎沒有出現,從不知道iOS 8。接下來你會怎麼做?回答一個java問題的評論,它不能在C#中工作嗎?:) – micantox 2015-08-02 11:43:10

+0

工作。好嚇人 – 2016-12-09 12:31:38

相關問題