标签:
Swift - CALayer的contents属性动画
效果
源码
https://github.com/YouXianMing/Swift-Animations
// // LiveImageView.swift // Swift-Animations // // Created by YouXianMing on 16/8/17. // Copyright © 2016年 YouXianMing. All rights reserved. // import UIKit // MARK: Public class : LiveImageView class LiveImageView: UIImageView { // MARK: Properties. /// Animation‘s duration. var duration : CFTimeInterval = 0.3 // MARK: Methods. /** Set image with animation or not. - parameter newVal: The new image. - parameter animated: Animated or not. */ func setImage(newVal : UIImage, animated : Bool) { if animated == true { let animation = CABasicAnimation(keyPath: "contents") animation.fromValue = image?.CGImage animation.toValue = newVal.CGImage animation.duration = duration pLayer.contents = image?.CGImage pLayer.addAnimation(animation, forKey: nil) image = newVal } else { image = newVal } } // MARK: Private value & func. private var pLayer : CALayer! override init(frame: CGRect) { super.init(frame: frame) pLayer = layer } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
// // LiveImageViewController.swift // Swift-Animations // // Created by YouXianMing on 16/8/17. // Copyright © 2016年 YouXianMing. All rights reserved. // import UIKit class LiveImageViewController: NormalTitleViewController { var timer : GCDTimer! = GCDTimer(inQueue: GCDQueue.mainQueue) var count : NSInteger! = 0 var images : [UIImage]! = [UIImage]() override func setup() { super.setup() images = [UIImage]() images.append(UIImage(named: "pic_1")!) images.append(UIImage(named: "pic_2")!) images.append(UIImage(named: "pic_3")!) images.append(UIImage(named: "pic_4")!) let image = images[0] let liveImageView = LiveImageView(frame: CGRectMake(0, 0, image.size.width, image.size.height)) liveImageView.center = (contentView?.middlePoint)! liveImageView.layer.borderWidth = 3 liveImageView.layer.borderColor = UIColor.blackColor().CGColor liveImageView.duration = 0.5 contentView?.addSubview(liveImageView) weak var wself = self timer.event({ let currentIndex = (wself?.count)! % (wself?.images.count)! wself?.count = (wself?.count)! + 1 liveImageView.setImage(wself!.images[currentIndex], animated: true) UIView.animateWithDuration(0.5, animations: { var tmpRect = liveImageView.bounds tmpRect.size = (liveImageView.image?.size)! liveImageView.bounds = tmpRect liveImageView.center = (wself?.contentView?.middlePoint)! }) }, timeIntervalWithSeconds: 1.0) timer.start() } }
标签:
原文地址:http://www.cnblogs.com/YouXianMing/p/5782165.html