Swift中使用CAAnimation实现图片缩放动画且保持原宽高
在Swift中用CAAnimation实现图片局部缩放且保持ImageView宽高的动画
你当前的代码使用transform.scale动画会缩放整个CALayer,导致UIImageView的宽高跟着变化。要实现只缩放图片内容、保持ImageView原始尺寸(即放大显示图片局部区域),需要调整动画的作用对象,针对layer的内容而非整个layer进行变换。
解决方案代码
// 先配置ImageView的内容模式,确保缩放时显示图片局部 imageView.contentMode = .center // 创建针对图片内容的缩放动画 let animation = CABasicAnimation(keyPath: "contentsTransform.scale") animation.fromValue = 1.4 animation.toValue = 1.0 animation.duration = 2 // 可选:让动画结束后保持最终状态,避免回弹 animation.fillMode = .forwards animation.isRemovedOnCompletion = false imageView.layer.add(animation, forKey: "contentScaleAnimation")
关键细节说明
- 改用
contentsTransform.scale作为动画的keyPath:这个属性仅作用于layer的内容(也就是图片),不会改变UIImageView本身的宽高布局。 - 配置
contentMode = .center:确保图片缩放时以中心为锚点,放大后显示中心区域的局部内容;如果需要其他锚点,比如左上角,可以调整layer的contentsCenter:// 设置左上角为内容锚点 imageView.layer.contentsCenter = CGRect(x: 0, y: 0, width: 1, height: 1) - 关于动画结束状态:如果不需要保持最终的缩放效果,可以去掉
fillMode和isRemovedOnCompletion的设置,动画结束后图片会恢复初始状态。
内容的提问来源于stack exchange,提问作者Ali AD
相关产品推荐
相关产品推荐

