use*_*522 4 core-animation ios swift3
我有一个imageview,我想让imageview以彩色动画.所以我的图像首先是绿色图像,然后我想将其设置为橙色图像.
这是我的代码:
class TestView: UIView {
func startAnimate(){
let size:CGSize = self.bounds.size
let layer = UIImageView(image: UIImage(named: "LaunchIcon"))
layer.frame = self.bounds
let initialRect:CGRect = CGRect.init(x: 0, y: size.height, width: size.width, height: 0)
let finalRect:CGRect = CGRect.init(x: 0, y: size.height, width: size.width, height: size.height)
let sublayer = CALayer()
sublayer.frame = initialRect
sublayer.backgroundColor = UIColor.orange.cgColor
sublayer.opacity = 0.5
let mask:CAShapeLayer = CAShapeLayer()
mask.frame = self.bounds
mask.path = UIBezierPath(rect: self.bounds).cgPath
mask.fillColor = UIColor.black.cgColor
layer.layer.addSublayer(sublayer)
layer.layer.mask = mask
self.layer.addSublayer(layer.layer)
let boundsAnim:CABasicAnimation = CABasicAnimation(keyPath: "bounds")
boundsAnim.toValue = NSValue.init(cgRect:finalRect)
let animationGroup = CAAnimationGroup()
animationGroup.animations = [boundsAnim]
animationGroup.isRemovedOnCompletion = false
animationGroup.duration = 2
animationGroup.fillMode = kCAFillModeForwards
sublayer.add(animationGroup, forKey: nil)
}
}
Run Code Online (Sandbox Code Playgroud)
我的结果:
第一个问题是橙色占据了整个画面,而不仅仅是我的画面.第二个问题是它没有填满顶部.
ale*_*nik 19
您的代码存在的一些问题:
您将一个矩形添加mask到图层,这根本不会影响渲染.你永远不会改变它的框架,位置,形状或其他任何东西,所以它的目的不明确.
sublayer应该只在你的玻璃形状内可见,对吧?但是在代码中你将它定义为一个rectengular,它是一个子视图,所以没有理由它会被你的玻璃图像的形状修剪.
请不要将views称为图层,对于正在阅读代码的人来说,这会让人感到困惑.如果它不是一个图层,请不要将其称为图层,这样简单.
let layer = UIImageView(image:UIImage(named:"LaunchIcon"))
CABasicAnimation工作方案:
实际上你不需要在这里使用CoreAnimation,你可以用更高级别的平面来实现它UIKit.在这种情况下,你最好的朋友是面具的财产UIView和animateWithDuration方法:
class GlassView: UIView {
let liquidView = UIView() //is going to be animated from bottom to top
let shapeView = UIImageView() //is going to mask everything with alpha mask
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
self.backgroundColor = UIColor.darkGray
self.liquidView.backgroundColor = UIColor.orange
self.shapeView.contentMode = .scaleAspectFit
self.shapeView.image = UIImage(named: "glass")
self.addSubview(liquidView)
self.mask = shapeView
layoutIfNeeded()
reset()
}
override func layoutSubviews() {
super.layoutSubviews()
liquidView.frame = self.bounds
shapeView.frame = self.bounds
}
func reset() {
liquidView.frame.origin.y = bounds.height
}
func animate() {
reset()
UIView.animate(withDuration: 1) {
self.liquidView.frame.origin.y = 0
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
实施细节:
视图的alpha通道决定了视图的内容和背景的显示量.完全或部分不透明的像素允许底层内容显示但完全透明的像素阻止该内容.
确保您的蒙版图像是.png并且在透明背景上包含形状.
| 归档时间: |
|
| 查看次数: |
2493 次 |
| 最近记录: |