我想在 UILabel
中组合图像和文本。为此,我使用了这部分代码:
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))
文字前景色为白色,但不幸的是图像仍为原始颜色。有趣的是,当我将第一行更改为此(初始化程序中的空格)时:
let attributedText = NSMutableAttributedString(string: " ")
然后一切正常。但问题是标签内的整个文本由于空格而偏移。如何在不添加空格的情况下更改图像颜色?
最佳答案
您必须使用图形上下文来反转颜色。我可能会将其作为 UIImage
的扩展。
示例swift代码如下。
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)
}
}
关于ios - 前景色不适用于属性文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47132886/