How to create UIBezierPath gradient fill?

2019-03-21 10:32发布

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

Here's an image of what I want to do:

enter image description here

As you can see, this square has:

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

How can I do this programatically without using pattern image color?

Here's 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];

1条回答
来,给爷笑一个
2楼-- · 2019-03-21 11:11

3 ways that I can think of.

  1. Create a CAGradientLayer and insert it as a sublayer of theView.layer. You can even put a rounded corner radius on the layer. Of course you'll have to import QuartzCore framework.

  2. Do it with CoreGraphics, like so:

    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);
    
  3. Create an off-screen image context that's one pixel wide and has a gradient, generate the image, then set the background color with colorWithPatternImage.

These are in order of easiest to hardest.

查看更多
登录 后发表回答