我有一个CGRect
值,需要在其周围画一个边框。我只希望在没有任何连接线的情况下绘制角。
像这样
我将如何使用swift绘制此图形?
最佳答案
这是一个自定义的UIView
类,它通过四个角进行绘制。您可以设置各种属性以获得所需的外观。
class CornerRect: UIView {
var color = UIColor.black {
didSet {
setNeedsDisplay()
}
}
var radius: CGFloat = 5 {
didSet {
setNeedsDisplay()
}
}
var thickness: CGFloat = 2 {
didSet {
setNeedsDisplay()
}
}
var length: CGFloat = 30 {
didSet {
setNeedsDisplay()
}
}
override func draw(_ rect: CGRect) {
color.set()
let t2 = thickness / 2
let path = UIBezierPath()
// Top left
path.move(to: CGPoint(x: t2, y: length + radius + t2))
path.addLine(to: CGPoint(x: t2, y: radius + t2))
path.addArc(withCenter: CGPoint(x: radius + t2, y: radius + t2), radius: radius, startAngle: CGFloat.pi, endAngle: CGFloat.pi * 3 / 2, clockwise: true)
path.addLine(to: CGPoint(x: length + radius + t2, y: t2))
// Top right
path.move(to: CGPoint(x: frame.width - t2, y: length + radius + t2))
path.addLine(to: CGPoint(x: frame.width - t2, y: radius + t2))
path.addArc(withCenter: CGPoint(x: frame.width - radius - t2, y: radius + t2), radius: radius, startAngle: 0, endAngle: CGFloat.pi * 3 / 2, clockwise: false)
path.addLine(to: CGPoint(x: frame.width - length - radius - t2, y: t2))
// Bottom left
path.move(to: CGPoint(x: t2, y: frame.height - length - radius - t2))
path.addLine(to: CGPoint(x: t2, y: frame.height - radius - t2))
path.addArc(withCenter: CGPoint(x: radius + t2, y: frame.height - radius - t2), radius: radius, startAngle: CGFloat.pi, endAngle: CGFloat.pi / 2, clockwise: false)
path.addLine(to: CGPoint(x: length + radius + t2, y: frame.height - t2))
// Bottom right
path.move(to: CGPoint(x: frame.width - t2, y: frame.height - length - radius - t2))
path.addLine(to: CGPoint(x: frame.width - t2, y: frame.height - radius - t2))
path.addArc(withCenter: CGPoint(x: frame.width - radius - t2, y: frame.height - radius - t2), radius: radius, startAngle: 0, endAngle: CGFloat.pi / 2, clockwise: true)
path.addLine(to: CGPoint(x: frame.width - length - radius - t2, y: frame.height - t2))
path.lineWidth = thickness
path.stroke()
}
}
用法示例:
let cr = CornerRect(frame: CGRect(x: 0, y: 0, width: 300, height: 500))
cr.color = .yellow
cr.thickness = 5
cr.backgroundColor = .white
将其复制并粘贴到操场上。为属性尝试不同的值。
关于ios - 如何仅绘制矩形的角(没有连接它们的线),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49089880/