I want to combine image and text inside UILabel
. To accomplish that I'm using this part of code:
let attributedText = NSMutableAttributedString(string: "")
let attachment = NSTextAttachment()
attachment.image = image.withRenderingMode(.alwaysTemplate)
attachment.bounds = CGRect(x: 0, y: 0, width: 20, height: 20)
attributedText.append(NSAttributedString(attachment: attachment))
attributedText.append(NSMutableAttributedString(string: "test",
attributedText.addAttribute(NSAttributedStringKey.foregroundColor,
value: UIColor.white,
range: NSMakeRange(0, attributedText.length))
Text has white foreground color, but unfortunately image is still in original color. Interestingly, when I change first line to this (whitespace inside initializer):
let attributedText = NSMutableAttributedString(string: " ")
then everything is working fine. But the problem is that whole text inside label has offset due to whitespace. How can I change image color without adding whitespace?
You would have to use graphics context to invert colors. I would probably have this as an extension on UIImage
.
Sample swift code is as follows.
extension UIImage {
func imageWithColor(color:UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height);
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context?.clip(to: rect, mask: self.cgImage!)
context?.setFillColor(color.cgColor)
context?.fill(rect)
let imageFromCurrentContext = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return UIImage(cgImage: imageFromCurrentContext!.cgImage!, scale: 1.0, orientation:.downMirrored)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With