iOS 绘制虚线框

- (void)setUpDashedBox2:(UIView *)view{
     CAShapeLayer *shapeLayer = [CAShapeLayer layer];
       [shapeLayer setBounds:view.bounds];
       [shapeLayer setPosition:view.center];
       [shapeLayer setFillColor:[[UIColor groupTableViewBackgroundColor] CGColor]];

       // 设置虚线颜色为blackColor
       [shapeLayer setStrokeColor:[[UIColor blackColor] CGColor]];
//       [shapeLayer setStrokeColor:[HMMainlColor CGColor]];

       // 3.0f设置虚线的宽度
       [shapeLayer setLineWidth:1.0f];
       [shapeLayer setLineJoin:kCALineJoinRound];

       // 3=线的宽度 1=每条线的间距
       [shapeLayer setLineDashPattern:
        [NSArray arrayWithObjects:[NSNumber numberWithInt:5],
         [NSNumber numberWithInt:3],nil]];

       // Setup the path
       CGMutablePathRef path = CGPathCreateMutable();

       CGPathMoveToPoint(path, NULL, 0, 3);
       CGPathAddLineToPoint(path, NULL, 45,3);

       CGPathMoveToPoint(path, NULL, 45, 3);
       CGPathAddLineToPoint(path, NULL,45, 45);

       CGPathMoveToPoint(path, NULL,45, 45);
       CGPathAddLineToPoint(path, NULL, 0, 45);

        CGPathMoveToPoint(path, NULL, 0, 45);
        CGPathAddLineToPoint(path, NULL, 0, 3);

       [shapeLayer setPath:path];
       CGPathRelease(path);
    [[view layer] addSublayer:shapeLayer];
}

只需要设置虚线框的四个坐标(左上( 0, 3)、右上( 45, 3)、右下( 45, 45)、左下( 0, 45))。

你可能感兴趣的:(iOS 绘制虚线框)