Here is what I am trying to do:
The screenshot is taken from a 14Pro iPhone.
I need to display a profile pic of every user corresponding to his name in a UITableView.
Code:-
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imgName: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
imgName.image = returnUserNameLetters(name: "B L")
}
func returnUserNameLetters(name: String?) -> UIImage? {
let frame = CGRect(x: 0, y: 0, width: 50, height: 50)
let nameLabel = UILabel(frame: frame)
nameLabel.textAlignment = .center
nameLabel.backgroundColor = UIColor(red: 60/255, green: 160/255, blue:89/255, alpha: 1)
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
}
}
Question: How to create the same image without blur in the different frames as the original image(first screenshot)?
Can someone please explain to me create the same image without blur in the different frames, I’ve tried to draw these waves but no results yet.
Any help would be greatly appreciated.
Thanks in advance.
2
Answers
The image is blurry because you are drawing a very small, 50×50 image. You just need to draw a bigger image.
A simple solution would be to not hard code the frame of the label, and instead give a large font size, and then use
sizeToFit
to figure the frame out.Alternatively, draw the name manually. This allows for more finer-grained control over what is drawn. You can e.g. add some padding around the text.