Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreground color not working for attributed text

Tags:

ios

uilabel

swift

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?

like image 387
Nominalista Avatar asked Nov 06 '17 08:11

Nominalista


1 Answers

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)
    }
}
like image 101
Arun Balakrishnan Avatar answered Sep 30 '22 09:09

Arun Balakrishnan