iOS 有关字符串宽度,高度处理以及富文本显示问题

164 阅读1分钟

NSString *labelText = self.titleLabel.text;
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];

//设置字体
[attributedString addAttribute:NSFontAttributeName
                value:[UIFont systemFontOfSize:30.0f]
                range:NSMakeRange(6, 3)];

//设置颜色
[attrStr addAttribute:NSForegroundColorAttributeName
                value:[UIColor redColor]
                range:NSMakeRange(4, 3)];

//设置背景颜色
[attrStr addAttribute:NSBackgroundColorAttributeName
                value:[UIColor redColor]
                range:NSMakeRange(4, 3)];

//空心字
[attrStr addAttribute:NSStrokeColorAttributeName
                value:[UIColor redColor]
                range:NSMakeRange(4, 3)];  // 设置空心字描边颜色 要和NSStrokeWidthAttributeName设置描边宽度一起使用
[attrStr addAttribute:NSStrokeWidthAttributeName
                value:@1.5
                range:NSMakeRange(4, 3)]; 

//字间距
[attrStr addAttribute:NSKernAttributeName
                value:@10                    // NSNumber
                range:NSMakeRange(4, 3)];//字间距

//倾斜
[attrStr addAttribute:NSObliquenessAttributeName
                value:@(0.5f)          
                range:NSMakeRange(4, 3)];// 正值向右倾斜 负值向左倾斜

//拉伸
[attrStr addAttribute:NSExpansionAttributeName
                value:@(0.5f)      // 正值横向拉伸 负值横向压缩
                range:NSMakeRange(4, 3)];

//基线偏移
[attrStr addAttribute:NSBaselineOffsetAttributeName
                value:@(10)   // 正值上偏 负值下偏
                range:NSMakeRange(4, 3)];

//阴影
NSShadow *shadow = [[NSShadow alloc] init];  // NSShadow只有3个属性:阴影颜色,模糊半径和偏移
shadow.shadowOffset     = CGSizeMake(3, 3);   // 阴影偏移(X方向偏移和Y方向偏移)
shadow.shadowBlurRadius = 1.5;                // 模糊半径
shadow.shadowColor      = [UIColor redColor]; // 阴影颜色
[attrStr addAttribute:NSShadowAttributeName
                value:shadow
                range:NSMakeRange(4, 3)];

//书写方向
[attrStr addAttribute:NSWritingDirectionAttributeName
                value:@[@(NSWritingDirectionRightToLeft | NSWritingDirectionOverride)]
                range:NSMakeRange(0, 20)];


self.titleLabel.attributedText = attributedString;
self.titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;