Skip to content

Instantly share code, notes, and snippets.

@bteapot
Created April 27, 2021 11:20
Show Gist options
  • Save bteapot/a6bf3523bbc34813f5db2ba166fc0de3 to your computer and use it in GitHub Desktop.
Save bteapot/a6bf3523bbc34813f5db2ba166fc0de3 to your computer and use it in GitHub Desktop.
Debug UIView with plotting paper grid.
#if DEBUG
import Foundation
import UIKit
public final class Millimetrovka: UIView {
public required init(
frame: CGRect,
mm: CGFloat = 10,
cm: CGFloat = 50
) {
// параметры
self.mm = mm
self.cm = cm
// инициализируемся
super.init(frame: frame)
// свойства
self.isOpaque = false
self.backgroundColor = .clear
}
public convenience init() {
self.init(frame: .zero)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError() }
let mm: CGFloat
let cm: CGFloat
public override var frame: CGRect {
didSet {
self.setNeedsDisplay()
}
}
public override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {
return
}
// рисовалки линий
let vline = { (x: CGFloat) in
context.move(to: CGPoint(x: x, y: rect.minY))
context.addLine(to: CGPoint(x: x, y: rect.maxY))
context.strokePath()
}
let hline = { (y: CGFloat) in
context.move(to: CGPoint(x: rect.minX, y: y))
context.addLine(to: CGPoint(x: rect.maxX, y: y))
context.strokePath()
}
let stepper = { (color: UIColor, min: CGFloat, max: CGFloat, step: CGFloat, liner: (CGFloat) -> Void) in
context.setStrokeColor(color.cgColor)
context.setLineWidth(1)
var pos: CGFloat = (min / step).rounded(.up) * step
while pos <= max {
liner(pos)
pos += step
}
}
// свойства линий
context.setLineWidth(1)
// мелкая сетка
let mColor: UIColor = .init(hue: 0, saturation: 0, brightness: 0, alpha: 0.05)
stepper(
mColor,
rect.minX,
rect.maxX,
self.mm,
vline
)
stepper(
mColor,
rect.minY,
rect.maxY,
self.mm,
hline
)
// крупная сетка
let cColor: UIColor = .init(hue: 0, saturation: 0, brightness: 0, alpha: 0.1)
stepper(
cColor,
rect.minX,
rect.maxX,
self.cm,
vline
)
stepper(
cColor,
rect.minY,
rect.maxY,
self.cm,
hline
)
// рисовалка координат
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 6),
.foregroundColor: UIColor(hue: 0, saturation: 0, brightness: 0, alpha: 0.5),
]
let inset: CGFloat = 2
var x: CGFloat = (rect.minX / self.cm).rounded(.up) * self.cm
while x <= rect.maxX {
var y: CGFloat = (rect.minY / self.cm).rounded(.up) * self.cm
while y <= rect.maxY {
let text = String(format: "%.0f:%.0f", x, y)
let point = CGPoint(x: x + inset, y: y + inset)
(text as NSString).draw(at: point, withAttributes: attributes)
y += self.cm
}
x += self.cm
}
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment