15

I have a UIView which I want to have a radial gradient, and I'm wondering how to go about doing this?

Lorenzo B
  • 33,216
  • 24
  • 116
  • 190
Andrew
  • 15,935
  • 28
  • 121
  • 203
  • Here is a link for a stackoverflow answer with sample code of how to add a radial gradient: [Radial Gradient](http://stackoverflow.com/questions/422066/gradients-on-uiview-and-uilabels-on-iphone/422208#422208) – Paul N Nov 14 '11 at 17:45

5 Answers5

18

Swift 3 - @IBDesignable

I worked off Karlis and Alexander's answers. I aimed to simplify as much as possible. Such as removing color space and locations (nil) so the gradient uses the defaults.

How to Use

Step 1

Create file and add this code: import UIKit

@IBDesignable
class RadialGradientView: UIView {

    @IBInspectable var InsideColor: UIColor = UIColor.clear
    @IBInspectable var OutsideColor: UIColor = UIColor.clear

    override func draw(_ rect: CGRect) {
        let colors = [InsideColor.cgColor, OutsideColor.cgColor] as CFArray
        let endRadius = min(frame.width, frame.height) / 2
        let center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2)
        let gradient = CGGradient(colorsSpace: nil, colors: colors, locations: nil)
        UIGraphicsGetCurrentContext()!.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: endRadius, options: CGGradientDrawingOptions.drawsBeforeStartLocation)
    }
}

Step 2

On Storyboard, set the UIView to the above RadialGradientView in Identity Inspector: Custom Class

Step 3

Set the Inside Color and Outside Color for your gradient in Attributes Inspector and see the change on your Storyboard: Radial Gradient

(Note: I made the UIView on the Storyboard big enough to so it fills the entire

Mark Moeykens
  • 15,915
  • 6
  • 63
  • 62
  • Please don't post [identical answers](http://stackoverflow.com/a/41555703) to multiple questions. Post one good answer, then vote/flag to close the other questions as duplicates. If the question is not a duplicate, *tailor your answers to the question.* – Paul Roub Jan 09 '17 at 19:53
  • I gotcha, @PaulRoub, will do! Thanks for the suggestion. – Mark Moeykens Jan 09 '17 at 19:57
  • 4
    This helped me: let endRadius = sqrt(pow(frame.width/2, 2) + pow(frame.height/2, 2)) – ChikabuZ Feb 21 '17 at 13:35
16

First subclass a UIView:

@implementation UIRadialView

- (void)drawRect:(CGRect)rect
{
    // Setup view
    CGFloat colorComponents[] = {0.0, 0.0, 0.0, 1.0,   // First color:  R, G, B, ALPHA (currently opaque black)
                                 0.0, 0.0, 0.0, 0.0};  // Second color: R, G, B, ALPHA (currently transparent black)
    CGFloat locations[] = {0, 1}; // {0, 1) -> from center to outer edges, {1, 0} -> from outer edges to center
    CGFloat radius = MIN((self.bounds.size.height / 2), (self.bounds.size.width / 2));
    CGPoint center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);

    // Prepare a context and create a color space
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

    // Create gradient object from our color space, color components and locations
    CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, colorComponents, locations, 2);

    // Draw a gradient
    CGContextDrawRadialGradient(context, gradient, center, 0.0, center, radius, 0);
    CGContextRestoreGState(context);

    // Release objects
    CGColorSpaceRelease(colorSpace);
    CGGradientRelease(gradient);
}

@end

And then add it to your view:

UIRadialView *radialView = [[UIRadialView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
radialView.backgroundColor = [UIColor redColor];
[self.view addSubview:radialView];

Result:

Radial gradient view

Karlis
  • 1,870
  • 1
  • 15
  • 15
6

Here's Karlis' answer in Swift 3:

override func draw(_ rect: CGRect) {

    // Setup view
    let colors = [UIColor.white.cgColor, UIColor.black.cgColor] as CFArray
    let locations = [ 0.0, 1.0 ] as [CGFloat]
    let radius = min((self.bounds.size.height / 2), (self.bounds.size.width / 2))
    let center = CGPoint.init(x: self.bounds.size.width / 2, y: self.bounds.size.height / 2)

    // Prepare a context and create a color space
    let context = UIGraphicsGetCurrentContext()
    context!.saveGState()
    let colorSpace = CGColorSpaceCreateDeviceRGB()

    // Create gradient object from our color space, color components and locations
    let gradient = CGGradient.init(colorsSpace: colorSpace, colors: colors, locations: locations)

    // Draw a gradient
    context!.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: radius, options: CGGradientDrawingOptions(rawValue: 0))
    context?.restoreGState()
}
Alexander
  • 565
  • 9
  • 20
6

To do this you need to drop down to Core Graphics and use CGContextDrawRadialGradient.

Similar Stack Overflow Questions

How can I draw a sector with radial gradient (iphone)

How to draw a gradient line (fading in/out) with Core Graphics/iPhone?

Other Resources

There's a tutorial showing how to draw icons with gradients on iOS here:

http://redartisan.com/2011/05/13/porting-iconapp-core-graphics

He's put the code on Github, complete with a UIView subclass that shows the (rather longwinded) way of making gradients using Core Graphics:

https://github.com/crafterm/IconApp/blob/master/IconApp/IconView.m

Community
  • 1
  • 1
John Gallagher
  • 6,208
  • 6
  • 40
  • 75
1

Here's Karlis answer in c# for Xamarin.iOS. Here I am specifying the colors directly but you can of course implement it the same way Karlis did.

public class RadialView : UIView
{
    public RadialView(CGRect rect) : base (rect)
    {
        this.BackgroundColor = UIColor.DarkGray;
    }

    public override void Draw(CGRect rect)
    {
        CGColor[] colorComponents = { UIColor.DarkGray.CGColor, UIColor.LightGray.CGColor };
        var locations = new nfloat[]{ 1, 0 }; 
        var radius = this.Bounds.Size.Height / 2;
        CGPoint center = new CGPoint(this.Bounds.Size.Width / 2, this.Bounds.Size.Height / 2);

        var context = UIGraphics.GetCurrentContext();
        context.SaveState();
        var colorSpace = CGColorSpace.CreateDeviceRGB();

        CGGradient gradient = new CGGradient(colorSpace, colorComponents, locations);
        context.DrawRadialGradient(gradient, center, 0, center, radius, CGGradientDrawingOptions.None);

        context.RestoreState();
        colorSpace.Dispose();
        gradient.Dispose();
    }
}
c.lamont.dev
  • 693
  • 1
  • 6
  • 14