【问题标题】:How to adjust position of CAShapeLayer based upon device size?如何根据设备大小调整 CAShapeLayer 的位置?
【发布时间】:2020-06-10 16:34:25
【问题描述】:

我正在尝试创建一个 CAShapeLayer 动画,该动画在 UILabel 的框架周围绘制轮廓。代码如下:

 func newQuestionOutline() -> CAShapeLayer {

        let outlineShape = CAShapeLayer()
        outlineShape.isHidden = false
        let circularPath = UIBezierPath(roundedRect: questionLabel.frame, cornerRadius: 5)
        outlineShape.path = circularPath.cgPath
        outlineShape.fillColor = UIColor.clear.cgColor
        outlineShape.strokeColor = UIColor.yellow.cgColor
        outlineShape.lineWidth = 5
        outlineShape.strokeEnd = 0
        view.layer.addSublayer(outlineShape)

        return outlineShape

    }

    func newQuestionAnimation() {

        let outlineAnimation = CABasicAnimation(keyPath: "strokeEnd")
        outlineAnimation.toValue = 1
        outlineAnimation.duration = 5
        newQuestionOutline().add(outlineAnimation, forKey: "key")

    }

动画在 iPhone 11 的模拟器上运行时按预期执行,这是我在故事板中使用的设备尺寸。但是,当在具有不同屏幕尺寸的不同设备(如 iPhone 8 plus)上运行项目时,形状会被画出位置,而不是像应有的那样围绕 UILabel 绘制。我使用自动布局将 UILabel 水平和垂直居中到视图的中心,因此无论使用什么设备, UILabel 都会居中。

有什么建议吗?提前致谢!

干杯!

【问题讨论】:

    标签: swift xcode swift4 swift5 cashapelayer


    【解决方案1】:

    形状层不是视图,因此不受自动布局的影响。任何时候你说像roundedRect: questionLabel.frame 这样的话,你就让自己依赖于questionLabel.frame 在那个时刻是什么,这是一个巨大的错误,因为这正是在自动布局确定什么之前无法确定的。框架将是(如果自动布局由于条件变化(例如旋转等)而改变主意,则可以在以后更改)

    有两种解决方案:

    • 在视图中托管形状层。现在你有了一些受自动布局影响的东西。每当视图更改其框架时,您仍然需要重绘形状图层,但您可以检测到并执行重绘。

    • 实现视图控制器的viewDidLayoutSubviews 以检测自动布局刚刚完成其工作。通过(例如)移除形状图层并根据当前条件制作一个新图层来做出响应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 2015-06-20
      • 2019-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多