Draw dotted (not dashed!) line, with IBDesignable in 2017

前端 未结 10 1701
死守一世寂寞
死守一世寂寞 2020-11-28 03:25

It\'s easy to draw a dashed line with UIKit. So:

CGFloat dashes[] = {4, 2};
[path setLineDash:dashes count:2 phase:0];
[path stroke];
         


        
10条回答
  •  情歌与酒
    2020-11-28 04:27

    Set the line cap style to round and set the “on” length to a tiny number.

    Swift playground example:

    import UIKit
    import PlaygroundSupport
    
    let path = UIBezierPath()
    path.move(to: CGPoint(x:10,y:10))
    path.addLine(to: CGPoint(x:290,y:10))
    path.lineWidth = 8
    
    let dashes: [CGFloat] = [0.001, path.lineWidth * 2]
    path.setLineDash(dashes, count: dashes.count, phase: 0)
    path.lineCapStyle = CGLineCap.round
    
    UIGraphicsBeginImageContextWithOptions(CGSize(width:300, height:20), false, 2)
    
    UIColor.white.setFill()
    UIGraphicsGetCurrentContext()!.fill(.infinite)
    
    UIColor.black.setStroke()
    path.stroke()
    
    let image = UIGraphicsGetImageFromCurrentImageContext()
    let view = UIImageView(image: image)
    PlaygroundPage.current.liveView = view
    
    UIGraphicsEndImageContext()
    

    Result:

    dots


    For objective-C, using the same example class as in the question, simply add

    CGContextSetLineCap(cx, kCGLineCapRound);
    

    before the call to CGContextStrokePath, and change the ra array values to match my Swift code.

提交回复
热议问题