Как установить цвет шаблонного изображения в NSTextAttachment
Как установить цвет шаблонного изображения, который является вложением в атрибутной строке?
Фон:
У меня есть UILabel, и я устанавливаю свой атрибутText в NSAttributedString. NSAttributedString включает в себя NSTextAttachment с небольшим изображением. Теперь я хочу, чтобы мой цвет изображения соответствовал цвету текста, и я не могу понять, как заставить его работать.
Я обычно ожидал бы цвет изображения, установив его режим рендеринга в UIImageRenderingModeAlwaysTemplate, а затем установив tintColor в содержащий UIView. Я попытался установить tintColor на свой UILabel, но это не имеет никакого эффекта.
Вот мой код. Это в Ruby (RubyMotion), поэтому синтаксис может выглядеть немного забавным, но он отображает 1:1 с Objective C.
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
Ответы
Ответ 1
Кажется, в 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;
}
Ответ 2
У меня есть хороший опыт использования библиотеки UIImage+Additions
при тонировании UIImage. Вы можете найти его здесь: 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 пойти из:
![UIImage before tinting]()
Для
![UIImage after tinting]()
Обновление: версия 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
}
Ответ 3
Решение @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
Я нашел лучшее решение.
Убедитесь, что в первом элементе находится простой текст: если 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];
Ответ 5
Я использую это расширение 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?
и проверить обнуляемость при расширении.
Ответ 6
используйте UIImageRenderingModeAlwaysOriginal для исходного цвета изображения. UIImageRenderingModeAlwaysTemplate + установить цвет оттенка для пользовательского цвета.