效果图:
QQ20171122-113317.png
通过NSMutableAttributedString设置UILabel中文字的背景色:
//设置字体背景颜色
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];
设置阴影有两种方法:
方法一:
// 通过layer层设置阴影
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(100, 150, 200, 50)];
label2.text = @"layer层设置阴影";
label2.textColor = [UIColor blueColor];
label2.layer.shadowColor = [UIColor blackColor].CGColor;
label2.layer.shadowOffset = CGSizeMake(0, 0);
label2.layer.shadowOpacity = 1;
[self.view addSubview:label2];
方法二:
// 通过富文本设置阴影
NSShadow *shadow = [[NSShadow alloc] init];
shadow.shadowBlurRadius = 10.0;
shadow.shadowOffset = CGSizeMake(0, 0);
shadow.shadowColor = [UIColor blackColor];
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:@"富文本设置阴影" 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];