Jayasabeen Appukuttan
Jayasabeen Appukuttan

Reputation: 1440

Gradient fill in CAGradientLayer

enter image description here

I need to fill CAGradientLayer with radial fill to attain an out put like the above

Here is my code which I have tried

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

By this code i get the below out put

enter image description here

If any solution available please do answer

Thanks in advance

Upvotes: 0

Views: 43

Answers (1)

DonMag
DonMag

Reputation: 77568

This may be close to what you want. It's a custom IB_DESIGNABLE view, so you can see it in 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

Result in IB:

enter image description here

Note: the light-blue color you see is the viewController view's background. The actual SanjayView has a clear background.

Play around with the colors and locations until you get your desired result.

Upvotes: 2

Related Questions