利用CAShapeLayer在文字上画虚线(UILable举例)
今天看到朋友有个需求,是要在lab的文字下画虚线,感觉很有意思就用CAShapeLayer研究了下,来一起看看吧。
老样子直奔主题上代码:
[objc] view plaincopy
<embed id="ZeroClipboardMovie_1" src="https://csdnimg.cn/public/highlighter/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="16" height="16" name="ZeroClipboardMovie_1" align="middle" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=1&width=16&height=16" wmode="transparent" style="box-sizing: border-box;">
-
//
-
// ViewController.m
-
// DottedLineDemo
-
//
-
// Created by a111 on 16/3/16.
-
// Copyright © 2016年 司小文. All rights reserved.
-
//
-
import "ViewController.h"
-
@interface ViewController ()
-
@end
-
@implementation ViewController
- (void)viewDidLoad {
-
[super viewDidLoad];
-
self.view.backgroundColor = [UIColor blackColor];
-
[self makeDottedLine];
-
// Do any additional setup after loading the view, typically from a nib.
-
}
-
pragma mark 制作虚线
- (void)makeDottedLine{
-
//lab
-
NSString *str = @"此笙吥涣
的博客:https://www.jianshu.com/u/f61a34028316"; -
float strFont = 14.;
-
CGRect labRect = [str boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:strFont]} context:nil];
-
UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake((self.view.frame.size.width-labRect.size.width)/2, 100, labRect.size.width,labRect.size.height)];
-
lab.textColor = [UIColor whiteColor];
-
lab.text = str;
-
lab.font = [UIFont systemFontOfSize:strFont];
-
[self.view addSubview:lab];
-
//layer
-
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
-
[shapeLayer setBounds:lab.bounds];
-
[shapeLayer setPosition:lab.center];
-
[shapeLayer setFillColor:[[UIColor redColor] CGColor]];
-
//设置虚线的颜色 - 颜色请必须设置
-
[shapeLayer setStrokeColor:[[UIColor whiteColor] CGColor]];
-
//设置虚线的高度
-
[shapeLayer setLineWidth:1.0f];
-
//设置类型
-
[shapeLayer setLineJoin:kCALineJoinRound];
-
/*
-
10.f=每条虚线的长度
-
3.f=每两条线的之间的间距
-
*/
-
[shapeLayer setLineDashPattern:
-
[NSArray arrayWithObjects:[NSNumber numberWithInt:10.f],
-
[NSNumber numberWithInt:3.f],nil]];
-
// Setup the path
-
CGMutablePathRef path1 = CGPathCreateMutable();
-
/*
-
代表初始坐标的x,y
-
x:写-2,是为了视觉上,虚线比文字稍长一点。
-
y:要和下面的y一样。
-
*/
-
CGPathMoveToPoint(path1, NULL,-2, lab.frame.size.height);
-
/*
-
代表坐标的x,y
-
lab.frame.size.width+2:我觉得他代表的意思可以理解为线的长度。
-
lab.frame.size.height:要与上面的y大小一样,才能使平行的线,不然会画出斜线呦~
-
*/
-
CGPathAddLineToPoint(path1, NULL, lab.frame.size.width+2,lab.frame.size.height);
-
//赋值给shapeLayer
-
[shapeLayer setPath:path1];
-
//清除
-
CGPathRelease(path1);
-
//可以把self改成任何你想要的UIView.
-
[[self.view layer] addSublayer:shapeLayer];
-
}
- (void)didReceiveMemoryWarning {
-
[super didReceiveMemoryWarning];
-
// Dispose of any resources that can be recreated.
-
}
-
@end
效果图:
image感谢观看,学以致用更感谢。