Objective C 如何使径向渐变在视图中间淡化

How to make radial gradient to be faded in the middle of view in Objective C

我想制作如上图所示的径向渐变视图,但无法在中间淡入淡出,这是我的渐变代码。

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view_background.bounds;
gradient.colors = @[(id)[UIColor colorWithRed:0.93 green:0.95  blue:0.22 alpha:1].CGColor, (id)[UIColor colorWithRed:0.08 green:0.42 blue:0.32 alpha:1].CGColor];
gradient.endPoint = CGPointMake(0.0, 0.5);
gradient.startPoint = CGPointMake(0.5, 1.0);
[view_background.layer insertSublayer: gradient atIndex:0];

试试下面的代码。将 RadialGradientView 设为 IBDesignable.

RadialGradientView.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

IB_DESIGNABLE
@interface RadialGradientView : UIView

@end

NS_ASSUME_NONNULL_END

RadialGradientView.m

#import "RadialGradientView.h"
#import <CoreGraphics/CoreGraphics.h>

@implementation RadialGradientView

- (void)drawRect:(CGRect)rect {
    // Drawing code

    UIColor* radialColor = [[UIColor colorWithRed:0.93 green:0.95  blue:0.22 alpha:1] CGColor];
    UIColor* outerColor = [[UIColor colorWithRed:0.08 green:0.42 blue:0.32 alpha:1] CGColor];

    [self.layer setCornerRadius: 10.0];
    [self.layer setMasksToBounds:YES];

    NSArray* colors = [[NSArray alloc] initWithObjects: radialColor, outerColor, nil];
    CGFloat endRadius = sqrt(pow(self.frame.size.width / 1.9, 2) + pow(self.frame.size.height / 1.9, 2));
    CGPoint startCenter = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 12);
    CGPoint center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);
    CGGradientRef gradient = CGGradientCreateWithColors(nil, (CFArrayRef)colors, nil);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawRadialGradient(context, gradient, startCenter, 0.0, center, endRadius, 0);
}


@end

Swift

@IBDesignable class RadialGradientView: UIView {

    @IBInspectable var radialColor: UIColor = UIColor(red: 0.93, green: 0.95, blue: 0.22, alpha: 1.0)
    @IBInspectable var outerColor: UIColor = UIColor(red: 0.08, green: 0.42, blue: 0.32, alpha: 1.0)

    override func draw(_ rect: CGRect) {

        layer.cornerRadius = 10.0
        layer.masksToBounds = true

        let colors = [radialColor.cgColor, outerColor.cgColor]
        let endRadius = sqrt(pow(frame.width/1.9, 2) + pow(frame.height/1.9, 2))
        let startCenter = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 12)
        let center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2)
        let gradient = CGGradient(colorsSpace: nil, colors: colors as CFArray, locations: nil)
        let context = UIGraphicsGetCurrentContext()

        context?.drawRadialGradient(gradient!, startCenter: startCenter, startRadius: 0.0, endCenter: center, endRadius: endRadius, options: CGGradientDrawingOptions.drawsBeforeStartLocation)
    }
}

截图