使用UIKit很容易繪製虛線線條。所以:在2017年使用IBDesignable繪製虛線(不是虛線!)線條
CGFloat dashes[] = {4, 2};
[path setLineDash:dashes count:2 phase:0];
[path stroke];
有沒有什麼辦法的方式來畫一個真正的虛線?
任何想法?
由於這個問題是真的老了,沒有人置於滿@IBDesignable
的解決方案,這是...
希望這樣可以節省別人打字。
@IBDesignable class DottedVertical: UIView {
@IBInspectable var dotColor: UIColor = UIColor.etc
@IBInspectable var lowerHalfOnly: Bool = false
override func draw(_ rect: CGRect) {
// say you want 8 dots, with perfect fenceposting:
let totalCount = 8 + 8 - 1
let fullHeight = bounds.size.height
let width = bounds.size.width
let itemLength = fullHeight/CGFloat(totalCount)
let path = UIBezierPath()
let beginFromTop = CGFloat(0.0)
let top = CGPoint(x: width/2, y: beginFromTop)
let bottom = CGPoint(x: width/2, y: fullHeight)
path.move(to: top)
path.addLine(to: bottom)
path.lineWidth = width
let dashes: [CGFloat] = [itemLength, itemLength]
path.setLineDash(dashes, count: dashes.count, phase: 0)
// for ROUNDED dots, simply change to....
//let dashes: [CGFloat] = [0.0, itemLength * 2.0]
//path.lineCapStyle = CGLineCap.round
dotColor.setStroke()
path.stroke()
}
}
我把它做成垂直的,你可以很容易地改變。
只要把一個UIView場景;無論你希望的寬度如何,這將是虛線的寬度。
只需將類更改爲DottedVertical
即可。它將在故事板中正確渲染。
注意,對於塊(「TOTALCOUNT」等等...)導致完全的塊,所述像素的高度給出的示例代碼,與所述的UIView的端部匹配的正在創造這條線。
一定要勾選RobMayoff的答案,下面給出了點不是塊的兩行代碼。
這裏的畫斜線一個很好的方式! :) https://stackoverflow.com/a/45228178/294884 – Fattie 2018-02-13 14:07:27