How to create a gradient fill UIBezierPath?

I would like to create a UIBezierPath with 10px rounded corners and with gradient fill. How can I achieve this effect?

Here is an image of what I want to do:

enter image description here

As you can see, this square has:

  • 2px black frame
  • 10px rounded corners
  • red to green fill linear gradient

How can I do this programmatically without using the color of the picture image ?

This is how I create the path:

 UIBezierPath *border = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:10.0f]; [border setLineWidth:2]; [[UIColor blackColor] setStroke]; [border stroke]; [[UIColor redColor] setFill]; <-- what should I put here? [border fill]; 
+4
iphone core-graphics uibezierpath drawing
source share
1 answer

3 ways that I can think of.

  • Create a CAGradientLayer and paste it as a sublayer of theView.layer. You can even put a rounded corner radius on a layer. Of course, you have to import the QuartzCore infrastructure.

  • Do this using CoreGraphics, for example:

     CGGradientRef gradient; CGColorSpaceRef colorspace; size_t num_locations = 2; CGFloat locations[2] = { 0.0, 1.0 }; CGFloat components[8] = { 1.0, 0.0, 0.0, 1.0, // Start color 0.0, 1.0, 0.0, 1.0 }; // End color colorspace = CGColorSpaceCreateDeviceRGB(); gradient = CGGradientCreateWithColorComponents (colorspace, components, locations, num_locations); CGContextDrawLinearGradient (ctx, gradient, gradientStartPoint, gradientEndPoint, 0); CGGradientRelease(gradient); 
  • Create an off-screen image context that has one pixel and has a gradient, generate an image, and then set the background color using the color WithPatternImage.

They are in order the easiest is the hardest.

+4
source share

All Articles