[英]How to draw same size dotted line on UIView
有人可以指導我如何在 UIView 上為所有側面繪制相同大小的虛線嗎?
我正在使用下面的代碼來畫線。
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)
如上圖所示
如您所見,左右邊緣寬度的線寬與頂部和底部邊緣高度不同。 如果我想為下面的所有面做同樣的事情,有什么辦法嗎?
訣竅是用筆划寬度值的一半插入繪圖框。 或者一半的筆划將被視圖剪裁,因為貝塞爾路徑將筆划居中繪制線。
我還稍微改變了你的框架並移除了位置。 這是更新的代碼。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.