使用draw(in:withAttributes:)绘制字符串时是否可以为文本应用渐变颜色?
问题解答
结论
使用draw(in:withAttributes:)绘制字符串时,无法直接通过文本属性NSAttributedString.Key.foregroundColor传入渐变实现效果,因为该属性仅支持UIColor类型,不过可以通过以下两种方案实现渐变文字效果:
方案1:利用图形上下文裁剪混合实现(灵活性最高)
实现步骤:
- 首先调用
boundingRect(with:options:attributes:context:)计算出字符串的实际绘制边界 - 获取当前图形上下文并保存状态,避免后续操作影响其他绘制内容
- 使用任意不透明颜色作为前景色,调用
draw(in:withAttributes:)绘制字符串,此时绘制的文字作为后续渐变填充的遮罩 - 将图形上下文的混合模式设置为
.sourceIn,该模式下后续绘制的内容只会显示在已有不透明内容的区域(也就是文字区域) - 创建
CGGradient对象,在文字绘制的边界范围内填充对应方向的渐变 - 最后恢复图形上下文状态
示例核心代码(Swift 端):
let text = "待绘制的渐变文本" let font = UIFont.systemFont(ofSize: 20) // 计算文本实际绘制边界 let textRect = text.boundingRect( with: CGSize(width: 300, height: .greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil ) guard let context = UIGraphicsGetCurrentContext() else { return } context.saveGState() defer { context.restoreGState() } // 绘制文字作为遮罩 text.draw( in: textRect, withAttributes: [.font: font, .foregroundColor: UIColor.black] ) // 设置混合模式仅保留文字区域的绘制内容 context.setBlendMode(.sourceIn) // 绘制线性渐变 let colorSpace = CGColorSpaceCreateDeviceRGB() let colors = [UIColor.red.cgColor, UIColor.blue.cgColor] as CFArray let locations: [CGFloat] = [0, 1] guard let gradient = CGGradient( colorsSpace: colorSpace, colors: colors, locations: locations ) else { return } context.drawLinearGradient( gradient, start: CGPoint(x: 0, y: textRect.midY), end: CGPoint(x: textRect.maxX, y: textRect.midY), options: [] )
方案2:渐变转图案颜色直接传入属性(实现最简单)
实现步骤:
- 先按照字符串绘制区域的大小,渲染生成对应渐变效果的UIImage
- 将渐变图片封装为图案颜色
UIColor(patternImage: 渐变图片),作为foregroundColor的属性值传入文本属性字典 - 直接调用
draw(in:withAttributes:)即可生成渐变文字
注意:该方案需要保证生成的渐变图片尺寸和文字绘制边界尺寸完全一致,避免渐变错位或出现平铺效果,适合渐变样式固定、文本尺寸不会动态变化的场景。
内容的提问来源于stack exchange,提问作者Kishan Bhatiya
相关产品推荐
相关产品推荐

