我在UILabel上有这样的渐变:
但是,如果我更改父视图的高度,则渐变会像这样“破裂”:
这是我用来应用渐变的UILabel的扩展
extension UILabel {
func applyGradientWith(startColor: UIColor?, endColor: UIColor?) {
guard let endColor = endColor else {
self.textColor = startColor
return
}
let gradientText = self.text ?? ""
let name: String = NSAttributedStringKey.font.rawValue
let textSize: CGSize = gradientText.size(withAttributes: [NSAttributedString.Key(rawValue: name):self.font])
let width: CGFloat = textSize.width
let height: CGFloat = textSize.height
UIGraphicsBeginImageContext(CGSize(width: width, height: height))
guard let context = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
self.textColor = startColor
return
}
UIGraphicsPushContext(context)
let top = CGPoint.zero
let bottom = CGPoint(x: 0, y: height)
let colorspace = CGColorSpaceCreateDeviceRGB()
if let startColor = startColor,
let gradient = CGGradient(colorsSpace: colorspace, colors: [startColor.cgColor, endColor.cgColor] as CFArray, locations: [0.0, 1.0]) {
context.drawLinearGradient(gradient, start: top, end: bottom, options: CGGradientDrawingOptions.drawsAfterEndLocation)
} else {
self.textColor = startColor
return
}
UIGraphicsPopContext()
let gradientImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.textColor = UIColor(patternImage: gradientImage!)
}
}
有人知道梯度为什么会“断裂”吗?我怎样才能解决这个问题? 预先谢谢你。