【问题标题】:How do I position a CALayer in the center of a UIView in Swift?如何在 Swift 中将 CALayer 定位在 UIView 的中心?
【发布时间】:2020-10-10 03:26:12
【问题描述】:

我有这个 CALayer,它是一个我希望正好位于 UIView 中心的点。我有一个覆盖 2/3 屏幕的 UIView。我如何让点位于 UIView 的中间。下面的代码将点定位在我需要的位置上方一英寸处。这是我的代码:

func setupUI() {

    let lineShape1 = CAShapeLayer()

    let linePath1 = UIBezierPath.init(ovalIn: CGRect.init(x: 0, y: 0, width: 5, height: 5))
    lineShape1.path = linePath1.cgPath
    lineShape1.fillColor = UIColor.init(white: 0.7, alpha: 0.5).cgColor
    lineShape1.position = CGPoint(x: cameraView.frame.size.width / 2, y: cameraView.frame.size.height / 2)
    self.view.layer.addSublayer(lineShape1)

}

【问题讨论】:

  • 您没有提供足够的信息。什么lineShape1
  • 另外如果你想把这个东西放在cameraView的中间,为什么要加到self.view呢?
  • 马上更新
  • 当我使用cameraView 时,由于某种原因,屏幕上没有显示点。
  • 因为您混淆了framebounds。将形状图层添加到cameraView 并放在cameraView.bounds 的中间,而不是cameraView.frame

标签: swift uiview calayer


【解决方案1】:

您混淆了框架和边界。设置成这样

func setupUI() {

    let lineShape1 = CAShapeLayer()

    let linePath1 = UIBezierPath.init(ovalIn: CGRect.init(x: 0, y: 0, width: 5, height: 5))
    lineShape1.path = linePath1.cgPath
    lineShape1.fillColor = UIColor.init(white: 0.7, alpha: 0.5).cgColor
    lineShape1.position = CGPoint(x: view.bounds.midX, y: view.bounds.midY)
    
   view.layer.addSublayer(lineShape1)

}

【讨论】:

  • 我不是必须使用cameraView而不是view来获取cameraView的中心吗?
  • 您是在视图中添加它还是在相机视图中添加它?要将其居中以查看还是相机查看?
  • 我想把它放在 cameraView 的中心
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-24
  • 1970-01-01
  • 2013-09-09
  • 1970-01-01
  • 1970-01-01
  • 2011-01-07
  • 1970-01-01
相关资源
最近更新 更多