如何在mainView上应用变换后得到子视图的框架?

时间:2013-05-06 05:51:29

标签: ios uiview transform

我创建了UIView的mainView objcet并在其上添加了一个子视图。我在mainView上应用了变换以减小帧大小。但是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框架的子视图框架?

2 个答案:

答案 0 :(得分:8)

您所看到的是预期的行为。 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}}

答案 1 :(得分:2)

除了s1m0n答案之外,将变换矩阵应用于视图的美妙之处在于,您可以根据其原始坐标系统进行推理(在您的情况下,您可以使用非变换坐标系统处理subMainView)这就是为什么,即使subMainView的框架比mainView的变换框架大,它仍然不会越过父视图,因为它会自动转换)。这意味着当您拥有转换后的父视图(例如,旋转和缩放)并且您希望在相对于此父视图的特定点中添加子视图时,您不必首先跟踪先前的转换以便这样做。

如果您真的有兴趣根据转换坐标系知道子视图的框架,那么将相同的转换应用于子视图的矩形就足够了:

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

如果你然后NSLog CGRect,你将获得:

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

我认为,这是您正在寻找的价值观。我希望这能回答你的问题!

相关问题