简体   繁体   中英

Draw a dotted line with full width in swift?

I am trying to create a dotted line programatically. However the line doesn't go all the way across the screen.

I have been using this SO answer to help me construct my dotted line. This is the output that I get.

输出

Here is my code

extension UIView{
    func addDashedBorder() {
        //Create a CAShapeLayer
        let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.lineWidth = 2
        // passing an array with the values [2,3] sets a dash pattern that alternates between a 2-user-space-unit-long painted segment and a 3-user-space-unit-long unpainted segment
        shapeLayer.lineDashPattern = [2,3]

        let path = CGMutablePath()
        path.addLines(between: [CGPoint(x: 0, y: 0),
                                CGPoint(x: self.frame.width, y: 0)])
        shapeLayer.path = path
        layer.addSublayer(shapeLayer)


    }
}

How can I fix my code so that the line goes across the whole screen?

Use self.bounds.width rather than self.frame.width .

From UIView 's documentation:

frame

The frame rectangle, which describes the view's location and size in its superview’s coordinate system.

whereas:

bounds

The bounds rectangle, which describes the view's location and size in its own coordinate system.

Give frame to CAShapeLayer

extension UIView{
    func addDashedBorder() {
        //Create a CAShapeLayer
        let shapeLayer = CAShapeLayer()
        shapeLayer.frame = self.bounds
        shapeLayer.strokeColor = UIColor.red.cgColor
        shapeLayer.lineWidth = 2
        // passing an array with the values [2,3] sets a dash pattern that alternates between a 2-user-space-unit-long painted segment and a 3-user-space-unit-long unpainted segment
        shapeLayer.lineDashPattern = [2,3]

        let size = shapeLayer.frame.size
        let rightTop = CGPoint.zero
        let leftTop = CGPoint(x: size.width, y: 0)
        let leftBottom = CGPoint(x: size.width, y: size.height)
        let rightBottom = CGPoint(x: 0, y: size.height)

        let path = CGMutablePath()
        path.addLines(between: [rightTop, leftTop, rightBottom, rightTop])
        shapeLayer.path = path
        layer.addSublayer(shapeLayer)


    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM