August 17, 2015 - No Comments!

Drawing Zig Zag Lines in IOS

A nice little feature I was recently asked to implement to which I could find no obvious solution. A small code sample to help those in need of a similar solution.

UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0)
let context = UIGraphicsGetCurrentContext()
CGContextClearRect(context, view.bounds);
// Point A
var aX:CGFloat = point1.center.x
var aY:CGFloat = point1.center.y
// Point B
var bX:CGFloat = point2.center.x
var bY:CGFloat = point2.center.y
// Calculate vector from start to end point
let distX = bX - aX
let distY = bY - aY
let distance = sqrt((distX * distX) + (distY * distY))
let segments:CGFloat = round(distance / 20)
let radius:CGFloat = 5
// Calculate length of the above mentioned vector
let segmentLength = sqrt(distX * distX + distY * distY) / segments
// Calculate segment vector
let segmentX = distX / segments
let segmentY = distY / segments
// Calculate normal of the segment vector and multiply it with the given radius
let normalX = -segmentY / segmentLength * radius
let normalY = segmentX / segmentLength * radius
// Calculate start position of the zig-zag line
var oldX:CGFloat = aX + normalX;
var oldY:CGFloat = aY + normalY;
// Render the zig-zag line
for(var n = 1; n < Int(segments); n++) {
let newX:CGFloat = aX + CGFloat(n) * segmentX + ((n & 1) == 0 ? normalX : -normalX)
let newY:CGFloat = aY + CGFloat(n) * segmentY + ((n & 1) == 0 ? normalY : -normalY)
CGContextMoveToPoint(context, oldX, oldY)
CGContextAddLineToPoint(context, newX, newY)
oldX = newX
oldY = newY
}
UIGraphicsEndImageContext()

Published by: nick in Code Sample, IOS/ XCode, Mobile

Leave a Reply