如何根据设备尺寸调整CAShapeLayer的位置?

问题描述 投票:0回答:1

我正在尝试创建一个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个回答
0
投票

形状层不是视图,因此它不受自动布局的限制。每当您说出roundedRect: questionLabel.frame之类的内容时,您都在依赖questionLabel.frame是什么[,这是一个巨大的错误,因为在自动布局确定帧将要确定之前,这是不确定的是(并且可以在以后由于变化的条件(例如旋转等)改变自动布局而改变主意)

有两种解决方法:

  • 在视图中承载形状层。现在,您可以进行自动排版。每当视图更改框架时,您仍然需要重绘形状图层,但是您可以检测到该形状并执行重绘。
  • 实现您的视图控制器的viewDidLayoutSubviews以检测到自动布局已完成其工作。通过(例如)删除形状层并根据当前条件做出新的响应。
© www.soinside.com 2019 - 2024. All rights reserved.