OC-NSAttributedString

Agregar atributos a NSAttributedString

La relación entre text.stringValue y atribuidoStringValue

Agregar atributos mediante dict

NSTextField *text = [NSTextField alloc]init];
// 创建文本属性字典
    NSMutableDictionary *textAttributes = [NSMutableDictionary dictionary];
    
    // 设置字体属性
    NSFont *font = [NSFont fontWithName:@"Arial" size:30.0];
    textAttributes[NSFontAttributeName] = font;
    NSNumber *strokeWidth = @-2.0; // 描边宽度
    textAttributes[NSStrokeColorAttributeName] = [NSColor redColor];
    textAttributes[NSStrokeWidthAttributeName] = strokeWidth;
    textAttributes[NSTextEffectAttributeName] = NSTextEffectLetterpressStyle;//添加立体效果 如果启用了字体效果 就只有字体效果了 其他的字体属性都不生效 比如说颜色
    
    //创建NSAttributedString对象
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text.stringValue attributes:textAttributes];
    // 将 NSAttributedString 对象应用到 NSTextField
    text.attributedStringValue = attributedText;

Agregar directamente

NSTextField *text = [NSTextField alloc]init];
 NSMutableAttributedString *attributedString = [[[NSMutableAttributedString alloc] initWithString:@"你好"] autorelease];//创建NSMutableAttributedString对象
 //添加属性
[attributedString addAttribute:NSStrokeWidthAttributeName value:@-2.0 range:NSMakeRange(0, attributedString.length)];

[text setAttributedStringValue:attributedString];

Modificar fuente

Cómo cambiar la fuente normalmente

textField setFont:[NSFont systemFontOfSize:16]

NSFont *font = [NSFont fontWithName:@"Arial" size:size];

Especifique el tipo de fuente a través de una cadena y puede seleccionar el tamaño y el peso.

NSFontManager *fontManager = [NSFontManager sharedFontManager];//
NSFont *font = [fontManager fontWithFamily:@"Helvetica Neue" traits:NSFontBoldTrait weight:0.4 size:32];

[attributedString addAttributes:@{
    
    NSFontAttributeName: font} range:NSMakeRange(0, attributedString.length)];

Obtenga color a través de NSColorSpace

//在获取颜色的时候要先确定颜色空间
    CGFloat red, green, blue, alpha;
    NSColorSpace *colorSpace = [NSColorSpace genericRGBColorSpace];
    NSColor* textColor = [text.textColor colorUsingColorSpace:colorSpace];
    [textColor getRed:&red green:&green blue:&blue alpha:&alpha];

Supongo que te gusta

Origin blog.csdn.net/qq_43535469/article/details/131010523
Recomendado
Clasificación