[英]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.然而,这条线并不是 go 一直穿过屏幕。
I have been using this SO answer to help me construct my dotted line.我一直在使用这个SO 答案来帮助我构建我的虚线。 This is the output that I get.这是我得到的 output。
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
.使用self.bounds.width
而不是self.frame.width
。
From UIView
's documentation:来自UIView
的文档:
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
给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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.