如何设置作为属性字符串附件的模板化图像的颜色?
背景:
我有一个UILabel,我将其attributionText设置为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
答案 0 :(得分:33)
似乎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;
}
答案 1 :(得分:10)
我在使用UIImage的图片时使用库UIImage+Additions
有很好的经验。你可以在这里找到它:https://github.com/vilanovi/UIImage-Additions。特别检查第IV节。
如果无法添加第三方库,可以使用以下内容:
- (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从:
要
更新:Swift版本:
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
}
答案 2 :(得分:2)
在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
}
}
答案 3 :(得分: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;
答案 4 :(得分:1)
我将这个NSMutableAttributedString
扩展名用于Swift。
import UIKit
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: UIImage
更改为image: UIImage?
并检查扩展名是否为空。
答案 5 :(得分:1)
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 及更高版本)
答案 6 :(得分:0)
我找到了更好的解决方案。 确保纯文本在第一项中。如果NSTextAttachment(图像)在第一项中,则可以在NSTextAttachment之前插入一个空格字符串。 像这样的代码:
// creat image attachment
NSTextAttachment *imagettachment = [[NSTextAttachment alloc] init];
imagettachment.image = [[UIImage imageNamed:@"ImageName"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
NSAttributedString *imageAttchString = [NSAttributedString attributedStringWithAttachment:attachment];
// creat 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];
答案 7 :(得分:-3)
使用UIImageRenderingModeAlwaysOriginal获取原始图像颜色。 UIImageRenderingModeAlwaysTemplate +设置自定义颜色的色调。