天天看点

利用CAShapeLayer在文字上画虚线(UILable举例)

今天看到朋友有个需求,是要在lab的文字下画虚线,感觉很有意思就用CAShapeLayer研究了下,来一起看看吧。

老样子直奔主题上代码:

//
//  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 = @"司小文的博客:http://blog.csdn.net/siwen1990";
    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
           

效果图:

利用CAShapeLayer在文字上画虚线(UILable举例)

注释写的很清楚但是demo还是要奉上的:

CAShapeLayer画虚线-司小文 (提取码:e684)

感谢观看,学以致用更感谢。