抱歉,如果这个问题已在其他地方得到解答。我尝试在多个地方进行搜索,但找不到好的解决方案。我是 Swift 开发的初学者。
根据下面的代码,我创建一个 subview ,向其中添加一个椭圆形 ShapeLayer,然后通过移动其中心并增加其大小来为 subview 设置动画。
subview 的动画正确,但是 subview 内的 ShapeLayer 的大小没有改变。我希望红色椭圆形增加尺寸,类似于 subview 。如果能让我知道我缺少什么,我将非常感激。
class playGroundView: UIView {
override func draw(_ rect: CGRect) {
// Add a blue rectangle as subview
let startFrame = CGRect(x: self.frame.midX, y: self.frame.midY, width: 10, height: 20)
self.addSubview(UIView(frame: startFrame))
self.subviews[0].backgroundColor = UIColor.blue
// Create red oval shape that is bounded by blue rectangle
// Add red oval shape as sub-layer to blue rectangle view
let subView = self.subviews[0]
let ovalSymbol = UIBezierPath(ovalIn: subView.bounds)
let shapeLayer = CAShapeLayer()
shapeLayer.path = ovalSymbol.cgPath
shapeLayer.fillColor = UIColor.red.cgColor
shapeLayer.strokeColor = UIColor.red.cgColor
subView.layer.addSublayer(shapeLayer)
// Animate movement and increase in size of blue rectangle view
UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 3, delay: 0, options: [], animations: {
let endFrame = CGRect(x:self.frame.midX - 50, y:self.frame.midY - 50, width: 20, height: 40)
self.subviews[0].frame = endFrame
self.setNeedsLayout()
self.layoutIfNeeded()
})
}
}
最佳答案
好的,在花费更多时间研究并更好地了解 ViewController 和 UIView 类内部的内容之后,在这些类中输入以下内容对我有用:
ViewController类内部:UIViewController
override func viewDidLoad() {
super.viewDidLoad()
let startFrame = CGRect(x: playGround.frame.midX, y: playGround.frame.midY, width: 30, height: 60)
cardSubView = cardView(frame: startFrame)
playGround.addSubview(cardSubView!)
let endFrame = CGRect(x: playGround.frame.midX - 100, y: playGround.frame.midY - 100, width: 60, height: 120)
UIViewPropertyAnimator.runningPropertyAnimator(withDuration: 10, delay: 0, options: [], animations: {
self.cardSubView?.frame = endFrame
self.cardSubView?.layoutIfNeeded()
})
}
在 UIView 类中:
class cardView: UIView {
override func draw(_ rect: CGRect) {
let backGroundPath = UIBezierPath(rect: rect)
UIColor.blue.setFill()
backGroundPath.fill()
let ovalSymbol = UIBezierPath(ovalIn: rect)
UIColor.red.setFill()
ovalSymbol.fill()
}
}
这仍然会导致我的 iPhone 模拟器中动画结束时出现奇怪的帧阴影,但是在设备上运行时没有问题。
关于ios - 动画 UIView 时自动调整 CAShapeLayer 大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51915746/