Iphone 如何创建UIBezierPath渐变填充?

Iphone 如何创建UIBezierPath渐变填充?,iphone,drawing,core-graphics,uibezierpath,Iphone,Drawing,Core Graphics,Uibezierpath,我想创建一个带有10px圆角和渐变填充的UIBezierPath。我怎样才能达到这个效果 以下是我想做的事情的图像: 如您所见,该正方形具有: 2件黑色边框 10px圆角 红色到绿色线性渐变填充 如何在不使用图案图像颜色的情况下以编程方式执行此操作 以下是我创建路径的方式: UIBezierPath *border = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:10.0f]; [border setLi

我想创建一个带有10px圆角和渐变填充的
UIBezierPath
。我怎样才能达到这个效果

以下是我想做的事情的图像:

如您所见,该正方形具有:

  • 2件黑色边框
  • 10px圆角
  • 红色到绿色线性渐变填充
如何在不使用图案图像颜色的情况下以编程方式执行此操作

以下是我创建路径的方式:

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];
UIBezierPath*border=[UIBezierPath-bezierpath-withroundedrect:self.bounds-cornerRadius:10.0f];
[边框设置线宽:2];
[[UIColor blackColor]设定行程];
[边界笔划];

[[UIColor redColor]setFill] 我能想到的三种方法

  • 创建CAGradientLayer并将其作为View.layer的子层插入。甚至可以在图层上设置圆角半径。当然,您必须导入QuartzCore框架

  • 使用CoreGraphics进行此操作,如下所示:

    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);
    
  • 创建一个一像素宽且具有渐变的屏幕外图像上下文,生成图像,然后使用colorWithPatternImage设置背景色


  • 这些是按最简单到最难的顺序排列的

    谢谢!我会选择第二个选项。PS:我在你的答案中添加了代码块。记住:如果它在列表中,则需要在它前面加8个空格;)谢谢你的编辑。我知道有些事情我做得不对。在绘制渐变之前,别忘了添加路径和剪辑,这样渐变只在矩形内绘制。CGContextAddPath(ctx,border.CGPath);CGContextClip(ctx);