今天项目有个progressView 设置渐变色的需求,发现可以设置progressImage来实现,前提是生成渐变色的图片
Progress原文链接
以下是生成渐变色图片代码
public enum GradientOrientation {
case vertical
case horizontal
}
convenience init?(bounds: CGRect, colors: [UIColor], orientation: GradientOrientation = .horizontal) {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = bounds
gradientLayer.colors = colors.map({ $0.cgColor })
if orientation == .horizontal {
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5);
gradientLayer.endPoint = CGPoint(x: 1.0, y: 0.5);
}
UIGraphicsBeginImageContextWithOptions(gradientLayer.bounds.size, false, UIScreen.main.scale)
gradientLayer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let cgImage = image?.cgImage else { return nil }
self.init(cgImage: cgImage)
}
UILabel渐变色,也可以通过生成图片来实现
Swift
label.textColor = UIColor(patternImage: progressImage!)
OC
[UIColor colorWithPatternImage:[UIImage imageNamed:@"backImage.png"]];
网友评论