OC-NSAttributedString

给NSAttributedString添加属性

text.stringValue和attributedStringValue的关系

通过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;

直接添加

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];

修改font字体

正常更改字体的方法

textField setFont:[NSFont systemFontOfSize:16]

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

通过字符串指定字体类型,并可以选择size 和 weight

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)];

通过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];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值