效果圖:
通過NSMutableAttributedString設(shè)置UILabel中文字的背景色:
//設(shè)置字體背景顏色
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]init];
NSString *str1 = @"背景色";
NSDictionary *dictAttr1 = @{NSBackgroundColorAttributeName:[UIColor cyanColor]};
NSAttributedString *attr1 = [[NSAttributedString alloc]initWithString:str1 attributes:dictAttr1];
[attributedString appendAttributedString:attr1];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 200, 50)];
label.textColor = [UIColor blueColor];
label.attributedText = attributedString;
[self.view addSubview:label];
設(shè)置陰影有兩種方法:
方法一:
// 通過layer層設(shè)置陰影
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(100, 150, 200, 50)];
label2.text = @"layer層設(shè)置陰影";
label2.textColor = [UIColor blueColor];
label2.layer.shadowColor = [UIColor blackColor].CGColor;
label2.layer.shadowOffset = CGSizeMake(0, 0);
label2.layer.shadowOpacity = 1;
[self.view addSubview:label2];
方法二:
// 通過富文本設(shè)置陰影
NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowBlurRadius = 10.0;
shadow.shadowOffset = CGSizeMake(0, 0);
shadow.shadowColor = [UIColor blackColor];
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:@"富文本設(shè)置陰影" attributes:@{NSShadowAttributeName:shadow}];
UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(100, 200, 200, 50)];
label3.textColor = [UIColor blueColor];
label3.attributedText = attributedText;
[self.view addSubview:label3];
描邊需要繼承自UILabel以后重載- (void)drawRect:(CGRect)rect方法:
- (void)drawRect:(CGRect)rect {
CGSize shadowOffset = self.shadowOffset;
UIColor *textColor = self.textColor;
CGContextRef ref = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(ref, 1);
CGContextSetLineJoin(ref, kCGLineJoinRound);
CGContextSetTextDrawingMode(ref, kCGTextStroke);
self.textColor = [UIColor redColor];
[super drawRect:rect];
CGContextSetTextDrawingMode(ref, kCGTextFill);
self.textColor = textColor;
self.shadowOffset = CGSizeMake(0,0);
[super drawRect:rect];
self.shadowOffset = shadowOffset;
}
描邊的使用:
// 描邊
HYZLabel *label4 = [[HYZLabel alloc] initWithFrame:CGRectMake(100, 250, 200, 50)];
label4.text = @"描邊啊描邊";
label4.textColor = [UIColor blueColor];
label4.shadowOffset = CGSizeMake(0, 0);
[self.view addSubview:label4];