如何在旋转后调整CAGradientLayer的大小? [英] How to resize a CAGradientLayer after rotation?

查看:530
本文介绍了如何在旋转后调整CAGradientLayer的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在视图中添加了 CAGradientLayer 。当视图自动调整大小(例如旋转后)时,渐变图层不会调整大小。可以将渐变设置为与视图相同的自动调整大小吗?注意,我在视图中使用自动布局约束。

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.

这里是我在做什么:

    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];


推荐答案

这里有两种不同的方法来解决你的问题。 / p>

Here are two different ways to fix your problem.


  1. 设置 gradientLayer 一个实例变量,而不是局部变量。然后,重写视图类中的 layoutSubviews 以设置渐变图层的框架:

  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;
}


  • 创建 code>命名为 GradientView ,并覆盖其 + layerClass 方法以返回 [CAGradientLayer class] 。使用此视图来绘制您的渐变,而不是直接使用图层。然后设置渐变视图的 autoresizingMask (或如果你使用自动布局添加约束)。 查看此答案例如。

  • 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.

    创建 GradientView 类也会使调整大小在旋转期间正确运行,因此我建议使用该解决方案。

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

    这篇关于如何在旋转后调整CAGradientLayer的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆