實(shí)現(xiàn)效果:
通過(guò)拓展為ImageView添加點(diǎn)擊放大預(yù)覽展示,點(diǎn)擊預(yù)覽復(fù)原效果。
完整代碼
class EWImageAmplification: NSObject {
static let shared = EWImageAmplification()
/// 點(diǎn)擊放大方法
///
/// - Parameters:
/// - currentImageView: 要放大的imageView
/// - alpha: 背景透明度(0-1)
func scanBigImageWithImageView(currentImageView: UIImageView, alpha: CGFloat) {
let image = currentImageView.image
/// 獲取keyWindow
let window = UIApplication.shared.keyWindow
let backGroundView = UIView(frame: CGRect(x: 0, y: 0, width: EWidth, height: EHeight))
/// 記錄imageView初始frame,保證復(fù)原
oldFrame = currentImageView.convert(currentImageView.bounds, to: window)
let imageView = UIImageView(frame: oldFrame)
backGroundView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: alpha)
backGroundView.alpha = 0
imageView.image = image
imageView.contentMode = .scaleAspectFit
backGroundView.addSubview(imageView)
backGroundView.isUserInteractionEnabled = true
window?.addSubview(backGroundView)
/// 為背景View添加手勢(shì)方法进鸠,實(shí)現(xiàn)點(diǎn)擊復(fù)原
let tap: EWTap = EWTap(target: self, action: #selector(tapOnBackView(_:)))
tap.backView = backGroundView
tap.imageView = imageView
backGroundView.addGestureRecognizer(tap)
/// 實(shí)現(xiàn)動(dòng)畫(huà)效果
UIView.animate(withDuration: 0.4) {
let imageY: CGFloat = (EHeight - (image?.size.height)! * EWidth / (image?.size.width)!) * 0.5
let height = (image?.size.height)! * EWidth / (image?.size.width)!
imageView.frame = CGRect(x: 0, y: imageY, width: EWidth, height: height)
backGroundView.alpha = 1
}
}
/// 點(diǎn)擊背景手勢(shì)方法
///
/// - Parameter sender: 手勢(shì)
@objc private func tapOnBackView(_ sender: EWTap) {
UIView.animate(withDuration: 0.4, animations: {
sender.imageView?.frame = oldFrame
sender.backView?.alpha = 0
}, completion: { (_) in
sender.backView?.removeFromSuperview()
})
}
}
/// 自定義手勢(shì)類(lèi),實(shí)現(xiàn)手勢(shì)方法傳參
class EWTap: UITapGestureRecognizer {
var backView: UIView?
var imageView: UIImageView?
override init(target: Any?, action: Selector?) {
super.init(target: target, action: action)
}
}
使用方法示例:
將EWImageAmplification文件拖入項(xiàng)目,調(diào)用時(shí):
/// 為imageView添加手勢(shì)方法
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapOnImageView))
imageView.addGestureRecognizer(tap)
@objc private func tapOnImageView() {
EWImageAmplification.shared.scanBigImageWithImageView(currentImageView: imageView, alpha: 1)
}
demo地址: EWImageTapBig
有問(wèn)題歡迎探討.