如何确定 UIBezierPath 相对于其父视图的 arcCenter?

How do I determine the arcCenter for a UIBezierPath relative to its parent view?

我正在使用带有 UIBezierPath 的 CAShapeLayer 来制作圆形进度条。该代码需要一个基于 CGPoint 的 center 值。

let circleLayer = CAShapeLayer()
let circlePath = UIBezierPath(arcCenter: center, radius: 100, startAngle: -CGFloat.pi / 2, endAngle: 2 * CGFloat.pi, clockwise: true)

我手动设置的值如下:

let center = CGPoint(x: 70, y: 70)

但是这些值是相对于 superView 的,我需要使其相对于其父视图 UIView。

UIView 中的所有其他元素都使用程序化 UI 代码进行约束,如下所示:

sampleText.translatesAutoresizingMaskIntoConstraints = false
sampleText.topAnchor.constraint(equalTo: directionsTitle.bottomAnchor, constant: 0).isActive = true
sampleText.leadingAnchor.constraint(equalTo: timerFooter.leadingAnchor, constant: 8).isActive = true
sampleText.trailingAnchor.constraint(equalTo: timerFooter.trailingAnchor, constant: -8).isActive = true

固定值在一台设备上可能工作正常,但在更大或更小的设备上会不对齐。我的问题是,如何确定满足 CGPoint 所需值的 center 的 UIView 值?

我试过这个:

let centerX = view.centerXAnchor
let centerY = view.centerYAnchor
        
let center = CGPoint(x: centerX, y: centerY)

但是,这会引发错误:在调用初始化程序时没有完全匹配

下图反映了形状放置的相对位置。蓝色框表示我想要放置圆圈的所需 UI查看区域。

非常感谢有智慧的人提供建议。

听起来你想要 UIView 的 bounds 的中点我认为是 yourView.bounds.midXyourView.bounds.midY

视图的 bounds 是它自己的坐标 space。视图的 frame 是它在其父视图中的位置 space。

UIView 有像 convertPoint:toCoordinateSpace: 这样的方法,还有一些朋友可以在 space 之间转换点和矩形。

啊,好的,我想我明白你面临的问题是什么了。

我认为您的问题是您试图像使用 UIView 一样使用 CAShapeLayer。而在现实中,他们根本不会那样做。

您应该做的是创建一个 UIView 子类并将 CAShapeLayer 放在那里。现在你只需要担心 CAShapeLayer 如何适应它自己的 UIView 子类。

要将图层“定位”到其他视图中,您实际上根本不需要担心。您只需放置新的 UIView 子类,层就会随之移动。

例如

class MyProgressView: UIView {
  let circleLayer: CAShapeLayer

  // add the circleLayer
  // add properties for customising the circle layer
  // Position the circle layer in the centre of the MyProgressView frame
  // I'd suggest using `layoutSubviews` or something for this.
  // etc...
}

现在...实际上不需要定位“CircleLayer”。您只需将 MyProgressView 放置在您想要的位置,图层就是其中的一部分,因此将继续进行。

从您的屏幕截图来看,您似乎希望带有蓝色矩形的视图包含 circleLayer。如果是这种情况,那么将蓝色矩形视图设为您的自定义 UIView 子类并...完成。它现在将包含圆形视图。

RayWenderlich 有一些关于使用 CALayer 自定义视图的好东西...https://www.raywenderlich.com/10317653-calayer-tutorial-for-ios-getting-started#toc-anchor-002