旋转时将CALayer的大小/位置保持在UIView上

时间:2011-11-01 11:04:13

标签: iphone uiview calayer rotation

我有一个具有以下属性的UIImage:

imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; 
imageView.contentMode = UIViewContentModeScaleAspectFit;

稍后我会在给定位置的imageview中添加自定义CALayer

当我旋转我的imageview时,图像会缩放以适合(给定contentMode),但现在我的CALayer定位错误。显然只有Y位是错的。如何在旋转视图时正确地重新定位CALayer

1 个答案:

答案 0 :(得分:0)

据我所知,为了定位/布局自定义图层,您应该对imageview进行子类化并实现此方法:

- (void) layoutSublayersOfLayer:(CALayer*)layer
{
    [super layoutSublayersOfLayer:layer];

    self.customlayer.position = CGPointMake(
            self.bounds.size.width / 2, self.bounds.size.height / 2);
}

如果您不想将imageview子类化,可以尝试这种方式。 此代码应该在您的imageview-controller中:

- (void) viewDidLoad
{
    [super viewDidLoad];

    self.container = [CALayer layer];
    self.container.bounds = self.imageview.bounds;
    self.container.delegate = self;

    [self.container addSublayer:self.customlayer];
    [self.imageview.layer addSublayer:self.container];
}

- (void) layoutSublayersOfLayer:(CALayer*)layer    // this is layers delegate method
{
    if (layer == self.container)
    {
        self.customlayer.position = CGPointMake(self.container.bounds.size.width / 2, 
                                                self.container.bounds.size.height / 2);
    }
}