ios nsattributedstring nstextattachment

ios - Cómo configurar el color de la imagen con plantilla en NSTextAttachment



nsattributedstring (4)

La solución de @blazejmar funciona, pero es innecesaria. Todo lo que necesita hacer para que esto funcione es establecer el color después de que se hayan conectado las cadenas atribuidas. Aquí hay un ejemplo.

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;

¿Cómo puedo configurar el color de una imagen con plantilla que es un archivo adjunto en una cadena atribuida?

Fondo:

Tengo una UILabel y estoy configurando su Texto atribuido a una NSAttributedString. La NSAttributedString incluye un NSTextAttachment con una imagen pequeña. Ahora quiero hacer que el color de mi imagen coincida con el color del texto y no puedo averiguar cómo hacerlo funcionar.

Normalmente esperaría colorear la imagen estableciendo su modo de representación en UIImageRenderingModeAlwaysTemplate y luego configurando tintColor en la vista UIV que contiene. He intentado configurar el tintColor en mi UILabel pero eso no tiene ningún efecto.

Aquí está mi código. Está en Ruby (RubyMotion), por lo que la sintaxis puede parecer un poco divertida, pero se mapea 1: 1 con 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


Parece que hay un error en UIKit. Hay una solución para eso;]

Por alguna razón, debe agregar un espacio vacío antes de adjuntar la imagen para que funcione correctamente con UIImageRenderingModeAlwaysTemplate .

Entonces tu fragmento se vería así (el mío está en 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; }


Tengo una buena experiencia con el uso de la biblioteca UIImage+Additions al teñir UIImage. Puede encontrarlo aquí: https://github.com/vilanovi/UIImage-Additions . Verifique especialmente la sección IV.

Si agregar una biblioteca de terceros no es una opción, aquí hay algo para comenzar:

- (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; }

Esto hará que un UIImage pase de:

A


use UIImageRenderingModeAlwaysOriginal para el color de la imagen original. UIImageRenderingModeAlwaysTemplate + establece el color del tinte para un color personalizado.