你可以使用層和麪具做到這一點,但它實際上是更容易只設置與圖案像的UIColor的文本顏色。這段代碼有效,儘管子類UILabel可能會更好,併爲該類提供了一種應用和/或更新圖像的方法。我認爲這很容易,因爲我發現處理文本圖層有點麻煩,因爲標籤可以通過adjustsFontSizeToFitWidth改變字體大小。
override func viewDidLayoutSubviews() {
label.textColor = UIColor(patternImage: partialGradient(forViewSize: label.frame.size, proportion: 0.65))
}
func partialGradient(forViewSize size: CGSize, proportion p: CGFloat) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, 0)
let context = UIGraphicsGetCurrentContext()
context?.setFillColor(UIColor.darkGray.cgColor)
context?.fill(CGRect(origin: .zero, size: size))
let c1 = UIColor.orange.cgColor
let c2 = UIColor.red.cgColor
let top = CGPoint(x: 0, y: size.height * (1.0 - p))
let bottom = CGPoint(x: 0, y: size.height)
let colorspace = CGColorSpaceCreateDeviceRGB()
if let gradient = CGGradient(colorsSpace: colorspace, colors: [c1, c2] as CFArray, locations: [0.0, 1.0]){
// change 0.0 above to 1-p if you want the top of the gradient orange
context?.drawLinearGradient(gradient, start: top, end: bottom, options: CGGradientDrawingOptions.drawsAfterEndLocation)
}
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}