调整视图大小时,标签上的渐变中断

时间:2018-11-08 15:00:30

标签: swift uiimage uilabel

我在UILabel上有这样的渐变:

First gradient

但是,如果我更改父视图的高度,则渐变会像这样“破裂”:

Broken gradient

这是我用来应用渐变的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!)
}
}

有人知道梯度为什么会“断裂”吗?我怎样才能解决这个问题? 预先谢谢你。

0 个答案:

没有答案