How do I add a radial gradient to a UIView?

后端 未结 5 1840
你的背包
你的背包 2020-12-14 21:12

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

相关标签:
5条回答
  • 2020-12-14 21:16

    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:

    Step 3

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

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

    0 讨论(0)
  • 2020-12-14 21:17

    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:

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-14 21:30

    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()
    }
    
    0 讨论(0)
  • 2020-12-14 21:43

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题