我想使用CAShapeLayer将UILabel沿着绘制的线放置。
喜欢:
目前,我无法理解如何计算X和Y点,以将标签放置在考虑了计算角度的直线中心。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let linePath = UIBezierPath()
linePath.move(to: CGPoint(x: initialPoint.x, y: initialPoint.y))
linePath.addLine(to: CGPoint(x: finalPoint.x, y: finalPoint.y))
let lineLayer = CAShapeLayer()
lineLayer.lineWidth = lineWidth
lineLayer.strokeColor = UIColor.white.cgColor
lineLayer.lineCap = .round
lineLayer.path = linePath.cgPath
view.layer.insertSublayer(lineLayer, at: 0)
// X & Y don't place correctly
let label = UILabel(frame: CGRect(x: (initialPoint.x - finalPoint.x) / 2, y: (initialPoint.y - finalPoint.y) / 2, width: view.frame.width, height: view.frame.height))
let angle = atan2(finalPoint.x - initialPoint.x, finalPoint.y - initialPoint.y + navigationHeight)
label.textColor = .white
label.font = label.font.withSize(24.0)
label.text = "Text here"
label.transform = CGAffineTransform(rotationAngle: angle)
view.addSubview(label)
}