图片点击全屏预览+缩放(Swift 3.0)

2017-01-14 15:49:15来源:http://www.jianshu.com/p/9c0794081fa8作者:折光人点击

最近在接触Swift,觉得苹果对新语言还是很重视的,但网上很少有这方面的例子,所以想着从OC往Swift方向转型,把每一个Demo改成Swift语言,分享给大家,共同进步共同学习



直接上代码:


import UIKit
class ViewController: UIViewController ,UIScrollViewDelegate {
var scrollView:UIScrollView?
var lastImageView:UIImageView?
var originalFrame:CGRect!
var isDoubleTap:ObjCBool!
//使用sb拖控件显示图片
@IBOutlet weak var myImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
myImageView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer.init(target: self, action: #selector(showZoomImageView(tap:)))
self.myImageView.addGestureRecognizer(tap)
}
func showZoomImageView( tap : UITapGestureRecognizer) {
let bgView = UIScrollView.init(frame: UIScreen.main.bounds)
bgView.backgroundColor = UIColor.black
let tapBg = UITapGestureRecognizer.init(target: self, action: #selector(tapBgView(tapBgRecognizer:)))
bgView.addGestureRecognizer(tapBg)
let picView = tap.view as! UIImageView//view 强制转换uiimageView
let imageView = UIImageView.init()
imageView.image = picView.image;
imageView.frame = bgView.convert(picView.frame, from: self.view)
bgView.addSubview(imageView)
UIApplication.shared.keyWindow?.addSubview(bgView)
self.lastImageView = imageView
self.originalFrame = imageView.frame
self.scrollView = bgView
self.scrollView?.maximumZoomScale = 1.5
self.scrollView?.delegate = self
UIView.animate(
withDuration: 0.5,
delay: 0.0,
options: UIViewAnimationOptions.beginFromCurrentState,
animations: {
var frame = imageView.frame
frame.size.width = bgView.frame.size.width
frame.size.height = frame.size.width * ((imageView.image?.size.height)! / (imageView.image?.size.width)!)
frame.origin.x = 0
frame.origin.y = (bgView.frame.size.height - frame.size.height) * 0.5
imageView.frame = frame
}, completion: nil
)
}
func tapBgView(tapBgRecognizer:UITapGestureRecognizer)
{
self.scrollView?.contentOffset = CGPoint.zero
UIView.animate(withDuration: 0.5, animations: {
self.lastImageView?.frame = self.originalFrame
tapBgRecognizer.view?.backgroundColor = UIColor.clear
}) { (finished:Bool) in
tapBgRecognizer.view?.removeFromSuperview()
self.scrollView = nil
self.lastImageView = nil
}
}
//正确代理回调方法
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.lastImageView
}
//错误代理回调方法
// func viewForZoomingInScrollView(scrollView: UIScrollView!) -> UIView! {
// return self.lastImageView
// }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}


如果对代码有疑问可以提问,我有空可以帮忙回答,如果有更好的写法,也欢迎指出,共同学习




最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台