2013-05-06 43 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

相关问题