Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw a string with gradient colors

Is there a way to draw a string in NSView with gradient colors? Gradient is not a background, but the letters itself. Maybe some mask, or so?

(Actually, it's not a text, but an icon font).

like image 999
Dmitry Isaev Avatar asked Jun 13 '26 13:06

Dmitry Isaev


1 Answers

override func draw(_ rect: CGRect) {

    //Add gradient layer
    let gl = CAGradientLayer()
    gl.frame = rect
    gl.endPoint = CGPoint(x: 0, y: 0)
    gl.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]
    layer.addSublayer(gl)

    //create a text layer mask
    let tl = CATextLayer()
    tl.frame = rect
    tl.string = "My String in Gradient"

    //Add mask to gradient layer
    gl.mask = tl

}

The picture shows a text with gradient

Hope this helps!

like image 104
Alfred Avatar answered Jun 16 '26 10:06

Alfred



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!