Skip to content

Instantly share code, notes, and snippets.

@jemmons
Last active November 13, 2019 08:31
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jemmons/6bb863b11127b4a8b16c9a7b7653b72f to your computer and use it in GitHub Desktop.
Save jemmons/6bb863b11127b4a8b16c9a7b7653b72f to your computer and use it in GitHub Desktop.
Draws a `singlePixelLine` line above or below the given point, depending on `topBias`.
import UIKit
func singlePixelLine(at y: CGFloat, in rect: CGRect, topBias: Bool = true) {
let offset = pixelUnit/2.0
let adjustedY = round(from: y - offset, fraction: pixelUnit, down: topBias) + offset
let line = makeLine(at: adjustedY, in: rect)
strokePath(line, width: pixelUnit)
}
var pixelUnit: CGFloat {
return 1.0 / UIScreen.main().scale
}
func round(from: CGFloat, fraction: CGFloat, down: Bool = true) -> CGFloat {
let expanded = from / fraction
let rounded = (down ? floor : ceil)(expanded)
return rounded * fraction
}
func makeLine(at y: CGFloat, in rect: CGRect) -> UIBezierPath {
precondition((rect.minY...rect.maxY).contains(y))
let line = UIBezierPath()
line.move(to: CGPoint(x: rect.minX, y: y))
line.addLine(to: CGPoint(x: rect.maxX, y: y))
return line
}
func strokePath(_ path: UIBezierPath, width: CGFloat) {
path.lineWidth = width
print(path)
UIColor.blue().setStroke()
path.stroke()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment