2016-12-24 117 views
1

的一定高度欲波纹管实现从画面的效果 - 一个UILabel显示进度X为从底部到X%的标签的高度的的梯度。标签的其余(100-X)%将具有不同的颜色。的UILabel与颜色渐变到标签

desired effect

,自己目前进入我脑海的唯一的事情是创建两个UIViews一个带有灰色背景和一个用渐变的颜色。将渐变视图放在灰色视图上方并将其高度设置为与当前进度相匹配。然后只需使用标签作为这两个视图的掩码。为了更好的说明,我附上描述我建议的解决方案的图片虽然我不满意它,因为它不是很优雅。

suggested solution

是否有可能在不同的和更优雅的方式来实现这一目标?理想情况下,只需继承UILabel即可。

回答

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! 
} 

enter image description here

0

您可以继承UILabel并在draw(_ rect: CGRect)函数中绘制您想要的内容。或者,如果你想快速完成,你也可以继承子类并添加渐变子视图。不要忘记调整它在layoutSubviews()函数。

0

您可以将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) 

enter image description here