Foreground color does not work for text attribute

I want to combine image and text inside UILabel. For this, I use this part of the 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))

The text has a white foreground color, but unfortunately the image is still in its original color. Interestingly, when I change the first line to this line (space inside the initializer):

let attributedText = NSMutableAttributedString(string: " ")

then everything works fine. But the problem is that all the text inside the label is biased due to spaces. How to change image color without adding spaces?

+5
source share
3 answers

You will need to use a graphics context to invert colors. I would probably have this extension on UIImage.

An example of a quick 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)
    }
}
+4

, , ​​UIKit. , , , - , :

. - , . : https://github.com/vilanovi/UIImage-Additions

image.withRenderingMode(...) :

attachment.image = image.add_tintedImage(with: .white, style: ADDImageTintStyleKeepingAlpha)
+1

I ran into the same error and found that the following simple trick works:

let attributedText = NSMutableAttributedString(string: " ")
... edit your attributed string...
attributedText.replaceCharacters(in: NSRange(location: 0, length: 1), with: "")
0
source

Source: https://habr.com/ru/post/1688786/


All Articles