I was able to draw a dashed box, using the following code:
CAShapeLayer *shapeLayer = [CAShapeLayer layer]; CGRect shapeRect = CGRectMake(0.0f, 0.0f, 200.0f, 100.0f); [shapeLayer setBounds:shapeRect]; [shapeLayer setPosition:CGPointMake(self.coreImageView_.frameX, self.coreImageView_.frameBottom - self.coreImageView_.frameHeight/2)]; [shapeLayer setFillColor:[[UIColor clearColor] CGColor]]; [shapeLayer setStrokeColor:[[UIColor whiteColor] CGColor]]; [shapeLayer setLineWidth:2.0f]; [shapeLayer setLineJoin:kCALineJoinRound]; [shapeLayer setLineDashPattern: [NSArray arrayWithObjects:[NSNumber numberWithInt:5], [NSNumber numberWithInt:5], nil]];
Now if I want to just draw a dashed line from point X to point B, how should I modify this code?
Lines are drawn by first moving the path to a starting point of the line, then adding a line segment to a point:
CGContextBeginPath(context); CGContextMoveToPoint(context, 10.5f, 10.5f); CGContextAddLineToPoint(context, 20.5f, 20.5f); CGContextClosePath(context); CGContextDrawPath(context, kCGPathFillStroke);
For drawing dashed line, You need to use CAShapeLayer
CAShapeLayer *shapeLayer = [CAShapeLayer layer]; [shapeLayer setBounds:self.bounds]; [shapeLayer setPosition:self.center]; [shapeLayer setFillColor:[[UIColor clearColor] CGColor]]; [shapeLayer setStrokeColor:[[UIColor blackColor] CGColor]]; [shapeLayer setLineWidth:3.0f]; [shapeLayer setLineJoin:kCALineJoinRound]; [shapeLayer setLineDashPattern: [NSArray arrayWithObjects:[NSNumber numberWithInt:10], [NSNumber numberWithInt:5],nil]]; // Setup the path CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, 10, 10); CGPathAddLineToPoint(path, NULL, 100,100); [shapeLayer setPath:path]; CGPathRelease(path); [[self layer] addSublayer:shapeLayer];
Try this code, it works for me,
Swift 3.0
extension UIView { func addDashedLine(strokeColor: UIColor, lineWidth: CGFloat) { backgroundColor = .clear let shapeLayer = CAShapeLayer() shapeLayer.name = "DashedTopLine" shapeLayer.bounds = bounds shapeLayer.position = CGPoint(x: frame.width / 2, y: frame.height / 2) shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.strokeColor = strokeColor.cgColor shapeLayer.lineWidth = lineWidth shapeLayer.lineJoin = kCALineJoinRound shapeLayer.lineDashPattern = [4, 4] let path = CGMutablePath() path.move(to: CGPoint.zero) path.addLine(to: CGPoint(x: frame.width, y: 0)) shapeLayer.path = path layer.addSublayer(shapeLayer) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With