How to resize a CAGradientLayer after rotation?

荒凉一梦 提交于 2019-11-30 01:22:12

问题


I'm adding a CAGradientLayer to a view. When the view is auto-resized (such as after a rotation) the gradient layer is not resized. Can the gradient be set to auto-resize the same as the view? Note also that I am using auto-layout constraints in the view.

Here's what I'm doing:

    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = CGRectMake(0.0, 0.0, frame.size.width, frame.size.height);
    gradientLayer.colors = [NSArray arrayWithObjects:
                       (id)[[UIColor colorWithRed:255.0/255.0f green:255.0/255.0f blue:255.0/255.0f alpha:1.0f] CGColor],
                       (id)[[UIColor colorWithRed:233.0/255.0f green:233.0/255.0f blue:233.0/255.0f alpha:1.0f] CGColor], nil];

    [self.layer insertSublayer:gradientLayer atIndex:0];

回答1:


Here are two different ways to fix your problem.

  1. Make gradientLayer an instance variable instead of a local variable. Then, override layoutSubviews in your view class to set the frame of the gradient layer:

    - (void)layoutSubviews {
        [super layoutSubviews];
        _gradientLayer.frame = self.bounds;
    }
    
  2. Create a subclass of UIView named GradientView, and override its +layerClass method to return [CAGradientLayer class]. Use this view to draw your gradient instead of using a layer directly. Then set the gradient view's autoresizingMask (or add constraints to it if you are using auto layout). See this answer for an example.

Creating the GradientView class will also make the resizing behave correctly during rotation, so I recommend that solution.




回答2:


I resize the layer's bounds manually by overriding the setFrame: method of the view:

-(void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    _gradientLayer.bounds = CGRectMake(0, 0, CGRectGetWidth(frame), CGRectGetHeight(frame));
}


来源:https://stackoverflow.com/questions/15581374/how-to-resize-a-cagradientlayer-after-rotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!