Home > Enterprise >  How to draw same size dotted line on UIView
How to draw same size dotted line on UIView

Time:06-16

Can someone please guide how I can draw same size dotted line on UIView for all sides?

I am using below code to draw line.

let dashBorder = CAShapeLayer()
let frameSize = self.frame.size
let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)
dashBorder.bounds = shapeRect
dashBorder.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
dashBorder.fillColor = UIColor.clear.cgColor
dashBorder.strokeColor = UIColor.blue.cgColor
dashBorder.lineJoin = CAShapeLayerLineJoin.round
dashBorder.lineDashPattern = [3, 3]
dashBorder.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: 10.0).cgPath
layer.addSublayer(dashBorder)

enter image description here

It is shown as above

as you can see the line width for left and right edge width are not same as top and bottom edge height. Is there any way if I want to make same for all sides like below?

enter image description here

CodePudding user response:

The trick is to inset the drawing frame with half the value of stroke width. Or half of your stroke will be clipped by the view, since bezier path centers the stroke to drawing line.

I also change your frame slightly and removed position. Here is the updated code.

    let lineWidth = 3.0
    let dashBorder = CAShapeLayer()
    let frameSize = bounds.insetBy(dx: lineWidth/2, dy: lineWidth/2)
    dashBorder.frame = bounds
    dashBorder.fillColor = UIColor.clear.cgColor
    dashBorder.strokeColor = UIColor.blue.cgColor
    dashBorder.lineJoin = CAShapeLayerLineJoin.round
    dashBorder.lineDashPattern = [3, 3]
    dashBorder.lineWidth = lineWidth
    dashBorder.path = UIBezierPath(roundedRect: frameSize, cornerRadius: 10.0).cgPath
    layer.addSublayer(dashBorder)
  • Related