34

如何设置作为属性字符串附件的模板图像的颜色?

背景:

我有一个 UILabel 并将其属性文本设置为 NSAttributedString。NSAttributedString 包含一个带有小图像的 NSTextAttachment。现在我想让我的图像颜色与文本颜色匹配,但我不知道如何使它工作。

我通常希望通过将其渲染模式设置为 UIImageRenderingModeAlwaysTemplate 来为图像着色,然后在包含的 UIView 上设置 tintColor。我尝试在我的 UILabel 上设置 tintColor 但这没有效果。

这是我的代码。它在 Ruby (RubyMotion) 中,所以语法可能看起来有点滑稽,但它与 Objective C 1:1 映射。

attachment = NSTextAttachment.alloc.initWithData(nil, ofType: nil)
attachment.image = UIImage.imageNamed(icon_name).imageWithRenderingMode(UIImageRenderingModeAlwaysTemplate)

label_string = NSMutableAttributedString.attributedStringWithAttachment(attachment)
label_string.appendAttributedString(NSMutableAttributedString.alloc.initWithString('my text', attributes: { NSFontAttributeName => UIFont.preferredFontForTextStyle(UIFontTextStyleFootnote), NSForegroundColorAttributeName => foreground_color }))

label = UILabel.alloc.initWithFrame(CGRectZero)
label.tintColor = foreground_color
label.attributedText = label_string
label.textAlignment = NSTextAlignmentCenter
label.numberOfLines = 0
4

8 回答 8

42

UIKit 中似乎有一个错误。有一个解决方法;]

出于某种原因,您需要在图像附件之前附加空白空间以使其与UIImageRenderingModeAlwaysTemplate.

所以你的片段看起来像这样(我的在 ObjC 中):

- (NSAttributedString *)attributedStringWithValue:(NSString *)string image:(UIImage *)image {
    NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
    attachment.image = image;

    NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];
    NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithAttributedString:[[NSAttributedString alloc] initWithString:@" "]];
    [mutableAttributedString appendAttributedString:attachmentString];
    [mutableAttributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:0] range:NSMakeRange(0, mutableAttributedString.length)]; // Put font size 0 to prevent offset
    [mutableAttributedString addAttribute:NSForegroundColorAttributeName value:[UIColor whiteColor] range:NSMakeRange(0, mutableAttributedString.length)];
    [mutableAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:@" "]];

    NSAttributedString *ratingText = [[NSAttributedString alloc] initWithString:string];
    [mutableAttributedString appendAttributedString:ratingText];
    return mutableAttributedString;
}
于 2016-03-30T20:52:23.283 回答
18

我在为实例着色时使用该库有很好的经验。UIImage+AdditionsUIImage特别检查第四节。

如果添加第三方库不是一个选项,这里有一些可以帮助您入门的方法:

- (UIImage *)colorImage:(UIImage *)image color:(UIColor *)color
{
    UIGraphicsBeginImageContextWithOptions(image.size, NO, [UIScreen mainScreen].scale);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextTranslateCTM(context, 0, image.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);

    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGContextDrawImage(context, rect, image.CGImage);
    CGContextSetBlendMode(context, kCGBlendModeSourceIn);
    [color setFill];
    CGContextFillRect(context, rect);


    UIImage *coloredImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return coloredImage;
}

UIImage将从:

着色前的 UIImage

着色后的 UIImage

更新:斯威夫特版本:

extension UIImage {
    func colorImage(with color: UIColor) -> UIImage? {
        guard let cgImage = self.cgImage else { return nil }
        UIGraphicsBeginImageContext(self.size)
        let contextRef = UIGraphicsGetCurrentContext()

        contextRef?.translateBy(x: 0, y: self.size.height)
        contextRef?.scaleBy(x: 1.0, y: -1.0)
        let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)

        contextRef?.setBlendMode(CGBlendMode.normal)
        contextRef?.draw(cgImage, in: rect)
        contextRef?.setBlendMode(CGBlendMode.sourceIn)
        color.setFill()
        contextRef?.fill(rect)

        let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return coloredImage
    }
}
于 2015-03-13T20:38:32.593 回答
6

我将此NSMutableAttributedString扩展用于 Swift。

extension NSMutableAttributedString {
    func addImageAttachment(image: UIImage, font: UIFont, textColor: UIColor, size: CGSize? = nil) {
        let textAttributes: [NSAttributedString.Key: Any] = [
            .strokeColor: textColor,
            .foregroundColor: textColor,
            .font: font
        ]

        self.append(
            NSAttributedString.init(
                //U+200C (zero-width non-joiner) is a non-printing character. It will not paste unnecessary space.
                string: "\u{200c}",
                attributes: textAttributes
            )
        )

        let attachment = NSTextAttachment()
        attachment.image = image.withRenderingMode(.alwaysTemplate)
        //Uncomment to set size of image. 
        //P.S. font.capHeight sets height of image equal to font size.
        //let imageSize = size ?? CGSize.init(width: font.capHeight, height: font.capHeight)
        //attachment.bounds = CGRect(
        //    x: 0,
        //    y: 0,
        //    width: imageSize.width,
        //    height: imageSize.height
        //)
        let attachmentString = NSMutableAttributedString(attachment: attachment)
        attachmentString.addAttributes(
            textAttributes,
            range: NSMakeRange(
                0,
                attachmentString.length
            )
        )
        self.append(attachmentString)
    }
}

这是如何使用它。

let attributedString = NSMutableAttributedString()
if let image = UIImage.init(named: "image") {
    attributedString.addImageAttachment(image: image, font: .systemFont(ofSize: 14), textColor: .red)
}

您还可以将addImageAttachment' 参数更改image: UIImageimage: UIImage?并检查扩展中的可空性。

于 2019-09-05T10:14:30.413 回答
5

在 iOS 12 上,我们需要在图像前插入一个字符并设置该字符的前景色。但是,在 iOS 13 上,我们可以直接在包含我们的 NSTextAttachment 的 NSAttributedString 上设置前景色。

我在 iOS 12.3 和 iOS 13.3.1 上测试了以下扩展

extension NSMutableAttributedString {
    @discardableResult
    func sbs_append(_ image: UIImage, color: UIColor? = nil) -> Self {
        let attachment = NSTextAttachment()
        attachment.image = image
        let attachmentString = NSAttributedString(attachment: attachment)
        if let color = color {
            if #available(iOS 13, *) {} else {
                // On iOS 12 we need to add a character with a foreground color before the image,
                // in order for the image to get a color.
                let colorString = NSMutableAttributedString(string: "\0")
                colorString.addAttributes([.foregroundColor: color], range: NSRange(location: 0, length: colorString.length))
                append(colorString)
            }
            let attributedString = NSMutableAttributedString(attributedString: attachmentString)
            if #available(iOS 13, *) {
                // On iOS 13 we can set the foreground color of the image.
                attributedString.addAttributes([.foregroundColor: color], range: NSRange(location: 0, length: attributedString.length))
            }
            append(attributedString)
        } else {
            append(attachmentString)
        }
        return self
    }
}
于 2020-02-24T12:31:15.993 回答
4
let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(systemName: "magnifyingglass")
imageAttachment.image = imageAttachment.image?.withTintColor(UIColor(red: 1.00, green: 1.00, blue: 0.00, alpha: 1.00))

这应该可以工作(ios 13 及更高版本)

于 2021-07-27T19:16:37.743 回答
1

@blazejmar 的解决方案有效,但没有必要。为此,您需要做的就是在属性字符串连接后设置颜色。这是一个例子。

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [[UIImage imageNamed:@"ImageName"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];

NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];

NSString *string = @"Some text ";
NSRange range2 = NSMakeRange(string.length - 1, attachmentString.length);

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
[attributedString appendAttributedString:attachmentString];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range2];
self.label.attributedText = attributedString;
于 2017-10-03T10:59:57.273 回答
0

我找到了更好的解决方案。确保纯文本位于第一项中。如果NSTextAttachment(image) 是第一项,您可以在NSTextAttachment.

// create image attachment
NSTextAttachment *imageAttachment = [[NSTextAttachment alloc] init];
imageAttachment.image = [[UIImage imageNamed:@"ImageName"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
NSAttributedString *imageAttchString = [NSAttributedString attributedStringWithAttachment:attachment];

// create attributedString
NSString *string = @"Some text ";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];

// insert image 
[attributedString insertAttributedString:imageAttchString atIndex:0];
[attributedString insertAttributedString:[[NSAttributedString alloc] initWithString:@" "] atIndex:0];

label.attributedText =  attributedString;

// used
label.textColor = [UIColor redColor];
// or
label.textColor = [UIColor greenColor];
于 2019-08-28T03:04:16.693 回答
-3

使用 UIImageRenderingModeAlwaysOriginal 作为原始图像颜色。UIImageRenderingModeAlwaysTemplate + 为自定义颜色设置色调颜色。

于 2017-12-27T07:30:22.840 回答