我画了一个弧线,并对其添加了动作。如何使用此动作更改圆弧的半径? (例如:半径为30,在圆弧上单击,然后单击+10。再次单击并为-10)。我尝试更改半径,但没有结果。虽然此操作无法移动,但我不太了解为什么是。
这里是完整的类代码。
@IBDesignable class circleView: UIView {
typealias ArcAction = () -> Void
struct ArcInfo {
var outlinePath: UIBezierPath
var action: ArcAction
}
private var arcInfos: [ArcInfo]!
let bgShapeLayer = CAShapeLayer()
var redRadius: Float?
required init?(coder: NSCoder) {
super.init(coder: coder)
let recognizer = UITapGestureRecognizer(target: self, action: #selector(tap(_ :)))
addGestureRecognizer(recognizer)
}
override func draw(_ rect: CGRect) {
let fullCircle = CGFloat.pi * 2
let arcAngle = fullCircle * 1.5 / 6
var lastArcAngle = CGFloat.pi / 4.0 + CGFloat.pi //-CGFloat.pi
arcInfos = []
// Red Arc
func redArc( action: @escaping ArcAction) {
let path = UIBezierPath(arcCenter: CGPoint(x: rect.width/2, y: rect.height/2), radius: CGFloat(redRadius ?? 46), startAngle: lastArcAngle, endAngle: lastArcAngle + arcAngle, clockwise: true)
#colorLiteral(red: 0.7450980392, green: 0.007843137255, blue: 0.262745098, alpha: 1).setStroke()
path.lineWidth = 10
path.stroke()
lastArcAngle += arcAngle
// separators
#colorLiteral(red: 0.927436769, green: 0.9490308166, blue: 0.967099607, alpha: 1).setStroke()
let outlinePath = hitTestPath(for: path)
outlinePath.lineWidth = 3
outlinePath.stroke()
arcInfos.append(ArcInfo(outlinePath: outlinePath, action: action))
}
//Add Arc
redArc {
self.redRadius = 56
}
}
@objc func tap(_ recognizer: UITapGestureRecognizer) {
let location = recognizer.location(in: self)
if let hitPath = (arcInfos.first { $0.outlinePath.contains(location) }) {
hitPath.action()
print(hitPath)
}
}
func hitTestPath(for path: UIBezierPath) -> UIBezierPath {
let pathCopy = path.cgPath.copy(strokingWithWidth: 15, lineCap: .butt, lineJoin: .miter, miterLimit: 0)
return UIBezierPath(cgPath: pathCopy)
}
}
您需要触发UI更新...
if let hitPath = (arcInfos.first { $0.outlinePath.contains(location) }) {
hitPath.action()
// add this line
setNeedsDisplay()
print(hitPath)
}
注意:您的代码按原样从半径为46 ...开始,在添加该行后,它以半径为56进行重绘。