CAGradientLayer中的渐变填充

Gradient fill in CAGradientLayer

我需要用径向填充填充 CAGradientLayer 以获得像上面那样的输出

这是我试过的代码

CAGradientLayer *gradientLayer = [CAGradientLayer layer];
gradientLayer.frame = self.bounds;
gradientLayer.colors = @[(id)[UIColor blueColor].CGColor, (id)[UIColor greenColor].CGColor];
//    gradientLayer.type = kCAGradientLayerRadial;

通过这段代码我得到下面的输出

如果有任何可用的解决方案,请回答

提前致谢

这可能接近您想要的。这是自定义 IB_DESIGNABLE 视图,因此您可以在 IB / Storyboard 中看到它。


SanjayView.h

//
//  SanjayView.h
//
//  Created by Don Mag on 1/21/20.
//

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

IB_DESIGNABLE
@interface SanjayView : UIView

@end

NS_ASSUME_NONNULL_END

SanjayView.m

//
//  SanjayView.m
//
//  Created by Don Mag on 1/21/20.
//

#import "SanjayView.h"

@interface SanjayView ()
@property (strong, nonatomic) CAGradientLayer *gLayer;
@end

@implementation SanjayView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self commonInit];
    }
    return self;
}

- (void)prepareForInterfaceBuilder
{
    [super prepareForInterfaceBuilder];
    [self commonInit];
}

- (void)commonInit {

    self.backgroundColor = [UIColor clearColor];

    if (!_gLayer) {
        _gLayer = [CAGradientLayer new];
        [self.layer addSublayer:_gLayer];
    }

    _gLayer.type = kCAGradientLayerRadial;

    _gLayer.startPoint = CGPointMake(0.5, 0.5);
    _gLayer.endPoint = CGPointMake(1.0, 1.0);

    _gLayer.colors = @[
        (id)[UIColor whiteColor].CGColor,
        (id)[UIColor blueColor].CGColor,
        (id)[UIColor colorWithRed:0.0 green:0.5 blue:0.0 alpha:1.0].CGColor,
        (id)[UIColor greenColor].CGColor,
        (id)[UIColor clearColor].CGColor,
    ];

    _gLayer.locations = @[
            [NSNumber numberWithFloat:0.7],
            [NSNumber numberWithFloat:0.72],
            [NSNumber numberWithFloat:0.75],
            [NSNumber numberWithFloat:0.9],
            [NSNumber numberWithFloat:0.95],
    ];

}

- (void)layoutSubviews {
    [super layoutSubviews];
    _gLayer.frame = self.bounds;
}

@end

IB 成绩:

注意:您看到的淡蓝色是 viewController 视图的背景。实际SanjayView背景清晰

尝试各种颜色和位置,直到获得想要的结果。