iOS 使用CAShapeLayer给View添加虚线边框

 
  
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIView *view = [[UIView alloc] init]; [self.view addSubview:view]; view.backgroundColor = [UIColor redColor]; view.frame = CGRectMake(100, 100, 100, 100); [self addBorderToLayer:view]; } - (void)addBorderToLayer:(UIView *)view { CAShapeLayer *border = [CAShapeLayer layer]; // 线条颜色 border.strokeColor = [UIColor blackColor].CGColor; border.fillColor = nil; border.path = [UIBezierPath bezierPathWithRect:view.bounds].CGPath; border.frame = view.bounds; // 不要设太大 不然看不出效果 border.lineWidth = 1; border.lineCap = @"square"; // 第一个是 线条长度 第二个是间距 nil时为实线 border.lineDashPattern = @[@9, @4]; [view.layer addSublayer:border]; }

你可能感兴趣的:(iOS)