3

我创建了 mainView 对象UIView并在其上添加了一个子视图。我在 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>>

这里主视图的宽度是250,子视图的宽度是1000。但是当我在模拟器中得到输出时,子视图被正确占用,但它没有跨越主视图。怎么可能?转换后如何获取相对于主视图框架的子视图框架?

4

2 回答 2

9

你看到的是预期的行为。an 的框架UIView是相对于其父级的,因此当您对其父视图应用转换时,它不会改变。虽然视图也会出现“扭曲”,但框架不会反映变化,因为它相对于其父级仍处于完全相同的位置。
但是,我假设您希望获得相对于 topmost 的视图框架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}}
于 2013-05-12T20:00:53.293 回答
2

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

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

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

如果您然后 NSLog this CGRect,您将获得:

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

我相信,这就是您正在寻找的价值观。我希望这回答了你的问题!

于 2013-05-14T09:38:30.230 回答