Apply gradient to UILabel bgCOlor iOS swift
Problem:
I want to set the gradient color as background for UILabel.How can i achieve that?
Solution:
You can write an extension function as like below
extension UILabel {
func applyGradient(colors: [CGColor]) {
let gradientLayer = CAGradientLayer()
gradientLayer.colors = colors
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 1)
gradientLayer.frame = CGRect(x: 0, y: 0, width: self.bounds.size.width, height: self.bounds.size.height)
let renderer = UIGraphicsImageRenderer(size: self.bounds.size) // Specify the size you need
let gradientImage = renderer.image { context in
gradientLayer.render(in: context.cgContext)
}
self.backgroundColor = UIColor(patternImage: gradientImage)
}
}
You can call the extension as like below
mycell.lbl.applyGradient(colors: [UIColor().colorWithHexString(hexString: "#f4f4f4").cgColor, UIColor().colorWithHexString(hexString: "#b6b6b6").cgColor])
colowith hexstring extension as like below
extension UIColor {
func colorWithHexString(hexString: String) -> UIColor {
var colorString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
colorString = colorString.replacingOccurrences(of: "#", with: "").uppercased()
let alpha: CGFloat = 1.0
let red: CGFloat = colorComponentFrom(colorString: colorString, start: 0, length: 2)
let green: CGFloat = colorComponentFrom(colorString: colorString, start: 2, length: 2)
let blue: CGFloat = colorComponentFrom(colorString: colorString, start: 4, length: 2)
let color = UIColor(red: red, green: green, blue: blue, alpha: alpha)
return color
}
}
Comments
Post a Comment