How do I add a radial gradient to a UIView?
Asked Answered
P

5

15

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

Prudery answered 14/11, 2011 at 17:34 Comment(1)
Here is a link for a stackoverflow answer with sample code of how to add a radial gradient: Radial GradientAtingle
S
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

Selfconsequence answered 14/11, 2011 at 17:43 Comment(1)
The redartisan.com/2011/05/13/porting-iconapp-core-graphics link is no longer activeIcaria
A
19

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

Apollinaire answered 9/1, 2017 at 19:47 Comment(3)
Please don't post identical answers 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.Overmeasure
I gotcha, @PaulRoub, will do! Thanks for the suggestion.Apollinaire
This helped me: let endRadius = sqrt(pow(frame.width/2, 2) + pow(frame.height/2, 2))Novation
H
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

Huysmans answered 19/2, 2016 at 11:32 Comment(0)
S
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

Selfconsequence answered 14/11, 2011 at 17:43 Comment(1)
The redartisan.com/2011/05/13/porting-iconapp-core-graphics link is no longer activeIcaria
C
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()
}
Cachou answered 26/10, 2016 at 22:2 Comment(0)
A
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();
    }
}
Avarice answered 28/7, 2017 at 17:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.