旋转UIView包括CALayer边界和CALayer帧

时间:2011-09-01 16:21:16

标签: iphone cocoa-touch uiview core-animation calayer

我想使用UIDeviceOrientationDidChangeNotification旋转我的“containerView”UIView(屏幕截图中的半透明红框),然后稍后(旋转后)将子图层添加到视图的图层,但我发现只有containerView.layer的边界被调整大小,而不是containerView.layer的框架! :(

以下是肖像画的样子:

portrait

示例代码:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)viewDidAppear:(BOOL)animated
{
    CALayer *r = [CALayer layer];
    r.frame = CGRectMake(0, 0, 100, 100);
    r.contents = (id)[[UIImage imageNamed:@"r.png"] CGImage];
    [self.containerView.layer addSublayer:r];
}

- (void)deviceRotated:(NSNotification *)notification
{
    ...
    if (orientation == UIDeviceOrientationLandscapeLeft) {
        self.containerView.transform = CGAffineTransformMakeRotation(RADIANS(90));
        self.containerView.bounds = CGRectMake(0, 0, 411.0, 320.0);

        NSLog(@"container bounds: %@", NSStringFromCGRect(self.containerView.bounds));
        NSLog(@"container layer frame: %@", NSStringFromCGRect(self.containerView.layer.frame));
        NSLog(@"container layer bounds: %@", NSStringFromCGRect(self.containerView.layer.bounds));

        CALayer *testLayer = [CALayer layer];
        testLayer.backgroundColor = [[UIColor blueColor] CGColor];
        testLayer.bounds = self.containerView.layer.frame;
        testLayer.position = CGPointMake(CGRectGetMidX(testLayer.bounds), CGRectGetMidY(testLayer.bounds));
        [self.containerView.layer addSublayer:testLayer];
    }
}

,旋转后打印:

container bounds: {{0, 0}, {411, 320}}
container layer frame: {{0, 0}, {320, 411}}
container layer bounds: {{0, 0}, {411, 320}}

(注意图层的帧仍然是320宽,411高。)

所以现在看起来像:

landscape left

我还尝试在更改边界之前设置中心,但看起来像是:

landscape left with setting center

我知道containerView的图层没有自动调整大小,所以我尝试在变换后设置图层的框架...... self.containerView.layer.frame = self.containerView.bounds;然后打印出来:

container bounds: {{0, 0}, {320, 411}}
container layer frame: {{0, 0}, {411, 320}}
container layer bounds: {{0, 0}, {320, 411}}

看起来像:

landscape left and setting layer frame

哎呀!

对于所有视图,

autoResizesSubviews设置为YES,clipsToBounds设置为NO。我无法使用shouldAutorotateToInterfaceOrientation因为真正的应用会有相机预览,所以我希望根视图保持纵向。

我必须错过一些关于我如何在containerView上进行转换以使其图层的边界和框架相同的东西,但我无法弄清楚它是什么!任何帮助将不胜感激。

更新 - 修正:

将新添加的图层边界(testLayer.bounds)设置为contentView.layer.bounds INSTEAD contentView.layer.frame就可以了。 (因为转换contentView会使其layer.frame失效。)谢谢Michael!

修正:

contentView.layer.bounds instead of contentView.layer.frame

1 个答案:

答案 0 :(得分:2)

  self.containerView.bounds = CGRectMake(0, 0, 411.0, 320.0);

由于翻转的上下文,此处的设置错误。你把它设置得很宽,因为它翻了90度就会回到垂直状态。

相关问题