Make images with name initials like Gmail in Swift programmatically for iOS

后端 未结 8 2207
孤城傲影
孤城傲影 2021-02-05 18:03

I need to display a profile pic of every user corresponding to his name in a UITableView. Until the image is downloaded I need to show an image with his name\'s first alphabet l

8条回答
  •  情书的邮戳
    2021-02-05 18:27

    Updated :

         func imageWith(name: String?) -> UIImage? {
            let frame = CGRect(x: 0, y: 0, width: 50, height: 50)
            let nameLabel = UILabel(frame: frame)
            nameLabel.textAlignment = .center
            nameLabel.backgroundColor = .lightGray
            nameLabel.textColor = .white
            nameLabel.font = UIFont.boldSystemFont(ofSize: 20)
            var initials = ""
            if let initialsArray = name?.components(separatedBy: " ") {
                if let firstWord = initialsArray.first {
                    if let firstLetter = firstWord.first {
                        initials += String(firstLetter).capitalized }
                }
                if initialsArray.count > 1, let lastWord = initialsArray.last {
                    if let lastLetter = lastWord.first { initials += String(lastLetter).capitalized
                    }
                }
            } else {
                return nil
            }
            nameLabel.text = initials
            UIGraphicsBeginImageContext(frame.size)
            if let currentContext = UIGraphicsGetCurrentContext() {
                nameLabel.layer.render(in: currentContext)
                let nameImage = UIGraphicsGetImageFromCurrentImageContext()
                return nameImage
            }
            return nil
        }
    

    Reference

提交回复
热议问题