Home > Blockchain >  Create multicolor single letter (character) with Swift 5
Create multicolor single letter (character) with Swift 5

Time:05-24

I have a requirement to create colourful string where each letter should have multicolors / rainbow colors. Refer the attached image for better understanding. This need to create using Swift 5 (UIKit) coding for an iOS app's dashboard.

In web, there are multiple solutions for multicolored string, but each letter of the string contain single color only, therefore they won't served my purpose. Any suggestions must be appreciated.

multicolored letter/character prototype

CodePudding user response:

The steps are: make a CAGradientLayer, then:

view.layer.addSublayer(gradient)
view.addSubview(label)
view.mask = label

CodePudding user response:

class LoginViewController: UIViewController {
    
    lazy var gradientBG:GradientBg = {
        let bg = GradientBg()
        return bg
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        gradientBG.frame = view.frame
        view.addSubview(gradientBG)
        
        let label = UILabel(frame: view.bounds)
        label.text = "Hello World"
        label.font = UIFont.boldSystemFont(ofSize: 30)
        label.textAlignment = .center
        gradientBG.addSubview(label)
        gradientBG.mask = label
    }
}

class GradientBg:UIView {
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // Create a gradient layer
        let gradient = CAGradientLayer()

        // gradient colors in order which they will visually appear
        gradient.colors = [UIColor.red.cgColor, UIColor.blue.cgColor]

        // Gradient from left to right
        gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 1.0, y: 0.5)

        // set the gradient layer to the same size as the view
        gradient.frame = bounds
        // add the gradient layer to the views layer for rendering
        self.layer.addSublayer(gradient)
        
        // Create a label and add it as a subview
    }
}
  • Related