为 UIView 添加虚线边框

    CGFloat viewWidth = 150;
    CGFloat viewHeight = 150;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 100, viewWidth, viewHeight)];
    view.backgroundColor = [UIColor colorWithWhite:0.7 alpha:1];
    view.layer.cornerRadius = CGRectGetWidth(view.bounds)/2;
    CAShapeLayer *borderLayer = [CAShapeLayer layer];
    borderLayer.bounds = CGRectMake(0, 0, viewWidth, viewHeight);
    borderLayer.position = CGPointMake(CGRectGetMidX(view.bounds), CGRectGetMidY(view.bounds));
    borderLayer.path = [UIBezierPath bezierPathWithRoundedRect:borderLayer.bounds cornerRadius:CGRectGetWidth(borderLayer.bounds)/2].CGPath;
    borderLayer.lineWidth = 1. / [[UIScreen mainScreen] scale];
    //虚线边框
    borderLayer.lineDashPattern = @[@8, @8];
    //实线边框
    //borderLayer.lineDashPattern = nil;
    borderLayer.fillColor = [UIColor clearColor].CGColor;
    borderLayer.strokeColor = [UIColor redColor].CGColor;
    [view.layer addSublayer:borderLayer];
    
    [self.view addSubview:view];

可通过修改UIBezierPath来改变虚线框的路径。

你可能感兴趣的:(为 UIView 添加虚线边框)