简体   繁体   中英

CALayer auto resizing in iOS on device orientation change

I have added one more CALayer for Custom View ,The code is

hostedGraphLayer.frame = self.layer.bounds;
[self.layer addSublayer:hostedGraphLayer];

When device orientation changes view's layer's sublayer also rotated but it is not autoresizing with respect to view. Layer wont have autoresize property for iOS.

One of the answer already in stackOverFlow is CALayers didn't get resized on its UIView's bounds change. Why? In this case setting layer's frame on device orientation change ,layer wont autoresize with respect to its view in between rotation start and end, this can be seen clearly in simulator by toggling slow animation.

Is there any fix for this "When view is rotated its layers also get rotated and it should resize wrt its view".

No there is not built in fix for that Yet,

You have to change its frames .

correct me if i am wrong.

In the view attributes inspector, set the view mode to redraw.
查看属性检查器
The content will no longer adapt or align or even stretch, but will render along the animation.

What truly happens is it renders to the final position, and that render is stretched during the animation, but that's a trick pretty much invisible for the user :)

The trick above will call setNeedsDisplay on the background layer ( view.layer ) on view's frame change, but it's up to you to update its children . setNeedsDisplay a layer will not propagate to the sublayers.
Also those sublayers will not autoresize like the views.
If you really want that behavior, use views instead, or force redraw yourself by overriding the setNeedsDisplay method of the parent layer.

-(void)setNeedsDisplay
{
    [super setNeedsDisplay];
    for (CALayer *sublayer in self.sublayers) {
        [sublayer setNeedsDisplay];
    }
}

It all depends of what/how you need to redraw.

If you really want to use a layer as a background layer which matches the frame of your view, subclass UIView and override its class method +(Class)layerClass to return your layer class.

+(Class)layerClass
{
    return [MyCustomLayer class];
}

It will use your custom layer as default background layer
It's very powerful ;) I use it everywhere
Don't forget the Redraw attribute !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM