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

前端 未结 10 1715
死守一世寂寞
死守一世寂寞 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:05

    Hello guys this solution worked for me fine. I found somewhere and changed a bit to prevent console warnings.

    extension UIImage {
        static func drawDottedImage(width: CGFloat, height: CGFloat, color: UIColor) -> UIImage {
            let path = UIBezierPath()
            path.move(to: CGPoint(x: 1.0, y: 1.0))
            path.addLine(to: CGPoint(x: width, y: 1))
            path.lineWidth = 1.5           
            let dashes: [CGFloat] = [path.lineWidth, path.lineWidth * 5]
            path.setLineDash(dashes, count: 2, phase: 0)
            path.lineCapStyle = .butt
            UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, 2)
            color.setStroke()
            path.stroke()
    
            let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
    
            return image
        }
    }
    

    This is the result:

提交回复
热议问题