ios - Core Graphics - 将 CGGradient 与笔画和文本一起使用

标签 ios swift core-graphics gradient

下面是我创建特定渐变的代码:

     let newBlueOne = UIColor(red: 0.141, green: 0.776, blue: 0.863,     alpha: 1.000)
    let newBlueTwo = UIColor(red: 0.318, green: 0.290, blue: 0.616, alpha: 1.000)

这里是渐变本身的代码:

let newBlue = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [newBlue1.CGColor, newBlue2.CGColor], [0, 1])!

这是我要制作的矩形的代码:

      let rectanglePath = UIBezierPath(roundedRect: CGRect(x: 22, y: 35, width: 194, height: 38), cornerRadius: 19)
    CGContextSaveGState(context)
    rectanglePath.addClip()
    CGContextDrawLinearGradient(context, translucent1, CGPoint(x: 119, y: 35), CGPoint(x: 119, y: 73), CGGradientDrawingOptions())
    CGContextRestoreGState(context)
    rectanglePath.lineWidth = 1
    rectanglePath.stroke()

我想使用上面的 newBlue 渐变作为创建的这个矩形的描边颜色。我还想将一些文本的颜色更改为新的蓝色渐变。不幸的是,我不太明白。谁能帮忙?

感谢您的回复,并期待阅读它们。非常感谢:)

最佳答案

您不能直接描边带有渐变的路径。

要执行您想要的操作,您需要转到核心图形层,并使用 CGContext 函数。

首先,您创建路径,并设置其各种属性,例如线宽。

然后,您使用 CGContextReplacePathWithStrokedPath(context) 函数。在 CGContext 文档中查找它。

然后,您将生成的路径用作剪辑路径。

然后,您使用渐变绘制该区域。

像这样:

override  func  drawRect(rect: CGRect) {
    let newBlueOne = UIColor(red: 0.141, green: 0.776, blue: 0.863, alpha: 1.000)
    let newBlueTwo = UIColor(red: 0.318, green: 0.290, blue: 0.616, alpha: 1.000)
    let newBlue = CGGradientCreateWithColors(CGColorSpaceCreateDeviceRGB(), [newBlueOne.CGColor, newBlueTwo.CGColor], [0, 1])!

    let  lineWeight: CGFloat = 20.0

    let  context: CGContext = UIGraphicsGetCurrentContext()!

    let  rect: CGRect = CGRectMake(40.0, 40.0, 200.0, 200.0)
    CGContextAddRect(context, rect)
    CGContextSetLineWidth(context, lineWeight)
    CGContextReplacePathWithStrokedPath(context)
    CGContextClip(context)

    let  startPoint: CGPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect))
    let  endPoint: CGPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect))
    CGContextDrawLinearGradient(context, newBlue, startPoint, endPoint, CGGradientDrawingOptions(rawValue: 0))
}

我只讨论了绘制边框。我不知道文本。

关于ios - Core Graphics - 将 CGGradient 与笔画和文本一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38539631/

相关文章:

ios - Swift - 将文本添加到可调整大小的图像

cocoa - 创建快速查看风格的缩放效果

ios - iOS(ImageIO/等)是否支持渐进式 JPEG 渲染?

ios - PSCollectionView 调用委托(delegate)

ios - 当我在 iOS Xcode 项目中使用 ffmpeg 时,为什么会收到 Apple Mach-O 链接器 (ld) 错误?

ios - 我可以从解析中检索信息,也可以打印该数组,但是当我尝试将这些数组元素放入 tableviewcell 时,什么也没有显示

ios - 核心图形 subview 未清除

ios - 为什么 Locale.current.identifier 无效?

swift - Swift 中的 NSString 格式未达到预期效果

swift - 解析 Swift 字典的二级