iphone - 如何创建 UIBezierPath 渐变填充?

标签 iphone drawing core-graphics uibezierpath

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

这是我想要做的事情的图片:

enter image description here

如您所见,这个正方形有:

  • 2px 黑色边框
  • 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];

最佳答案

我能想到的三种方法。

  1. 创建一个 CAGradientLayer 并将其作为 theView.layer 的子图层插入。您甚至可以在图层上放置圆角半径。当然你必须导入 QuartzCore 框架。

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

这些按从最简单到最难的顺序排列。

关于iphone - 如何创建 UIBezierPath 渐变填充?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9249921/

相关文章:

objective-c - 使用 ARC 返回自动释放的 CFTypeRef

iphone - 键盘打开时在 ScrollView 中滚动(就像在 Notes 应用程序 iOS 中一样)

c# - 使用 WPF 绘制图像网格

iphone - 如何获取 Facebook 页面的更大头像

android - 在 Android 的按钮上画一条线?

Python TachoMeter,如何在每个 create_line 之后显示

ios - PaintCode 表达式中的引用封闭框架

objective-c - cocoa 事件水龙头

iphone - 如何从 iPhone 应用程序中添加联系人?

iphone - iOS - 在没有实际推送的情况下显示推送弹出窗口并播放推送声音