Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drawing dashed line using CALayer

Tags:

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?

like image 532
adit Avatar asked Oct 03 '12 04:10

adit


2 Answers

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]; 
like image 154
Lithu T.V Avatar answered Sep 25 '22 15:09

Lithu T.V


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)     } } 
like image 28
Patel Jigar Avatar answered Sep 24 '22 15:09

Patel Jigar