iOS 虚线框设置

NSString *text = @"守夜人誓言:「长夜将至,我从今开始守望,至死方休。我将不娶妻、不封地、不生子。我将不戴宝冠,不争荣宠。我将尽忠职守,生死於斯。我是黑暗中的利剑,长城上的守卫。我是抵御寒冷的烈焰,破晓时分的光线,唤醒眠者的号角,守护王国的坚盾。我将生命与荣耀献给守夜人,今夜如此,夜夜皆然。」";

//设置文本属性

NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc]init];

//设置行间距

[paraStyle setLineSpacing:5];

[paraStyle setLineBreakMode:NSLineBreakByWordWrapping];

//字体大小

UIFont *textFont = [UIFont systemFontOfSize:15];

//字体颜色

UIColor *textColor = [UIColor lightGrayColor];

NSDictionary *textDic = @{NSFontAttributeName : textFont,NSForegroundColorAttributeName : textColor,NSParagraphStyleAttributeName : paraStyle};

//富文本

NSAttributedString *attrText = [[NSAttributedString alloc]initWithString:text attributes:textDic];

//计算文本的size

CGSize textSize = [text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width *0.5, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:textDic context:nil].size;

UILabel *textLabel = [[UILabel alloc]init];

textLabel.attributedText = attrText;

textLabel.numberOfLines = 0;

[self.view addSubview:textLabel];

//布局

[textLabel mas_makeConstraints:^(MASConstraintMaker *make) {

make.center.mas_equalTo(self.view);

make.width.mas_equalTo(ceil(textSize.width));//

make.height.mas_equalTo(ceil(textSize.height));

}];

//设置虚线边框

CAShapeLayer *borderLayer = [CAShapeLayer layer];

borderLayer.bounds = CGRectMake(0, 0, textSize.width + 10, textSize.height + 10);

//中心点位置

borderLayer.position = CGPointMake(textSize.width *0.5, textSize.height *0.5);

borderLayer.path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, textSize.width + 10, textSize.height + 10)].CGPath;

//边框的宽度

borderLayer.lineWidth = 3;

//边框虚线线段的宽度

borderLayer.lineDashPattern = @[@5,@5];

borderLayer.fillColor = [UIColor clearColor].CGColor;

borderLayer.strokeColor = [UIColor purpleColor].CGColor;

[textLabel.layer addSublayer:borderLayer];

效果如下:

iOS 虚线框设置_第1张图片

你可能感兴趣的:(iOS 虚线框设置)