【问题标题】:UILabel with color gradient to certain height of the label带有颜色渐变到标签特定高度的 UILabel
【发布时间】:2016-12-24 12:09:06
【问题描述】:
我想实现下图的效果 - UILabel 将进度 X 显示为从底部到标签高度 X% 的渐变。标签的剩余 (100 - X)% 将具有不同的颜色。
我现在唯一想到的就是创建两个UIViews,一个是灰色背景,一个是渐变色。将渐变视图放在灰色视图之上,并设置它的高度以匹配当前进度。然后只需将标签用作这两个视图的掩码。为了更好地说明,我附上了一张描述我建议的解决方案的图片。虽然我对它不满意,因为它不是很优雅。
是否有可能以一种不同且更优雅的方式实现这一目标?理想情况下,只需将UILabel 子类化即可。
【问题讨论】:
标签:
ios
swift
uikit
uilabel
calayer
【解决方案1】:
您可以使用图层和蒙版来做到这一点,但实际上使用图案图像中的 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!
}
【解决方案2】:
您可以将 Core Animation 与 CATextLayer 和 CAGradientLayer 一起使用。
import PlaygroundSupport
let bgView = UIView(frame: CGRect(x: 0, y: 0, width: 80, height: 80))
bgView.backgroundColor = UIColor.black
PlaygroundPage.current.liveView = bgView
let textLayer = CATextLayer()
textLayer.frame = bgView.frame
textLayer.string = "70"
textLayer.fontSize = 60
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bgView.frame
gradientLayer.colors = [
UIColor.gray.cgColor,
UIColor(red: 1, green: 122.0/255.0, blue: 0, alpha: 1).cgColor,
UIColor(red: 249.0/255.0, green: 1, blue: 0, alpha: 1).cgColor
]
//Here you can adjust the filling
gradientLayer.locations = [0.5, 0.51, 1]
gradientLayer.mask = textLayer
bgView.layer.addSublayer(gradientLayer)
【解决方案3】:
您可以继承UILabel 并在draw(_ rect: CGRect) 函数中绘制您想要的内容。或者,如果您想快速做到这一点,您也可以进行子类化并添加渐变子视图。不要忘记在layoutSubviews() 函数中调整它的大小。