我一直在关注一篇文章,该文章显示了如何重现Instagram对图像的缩放。它工作正常,但是当我缩放时,图像不会超出ImageView的范围。正如您在屏幕截图中所看到的那样,这看起来很奇怪,我希望它与Instagram一样,如果需要,可以将“图像”缩放到整个屏幕,然后重新发布(已开始工作)。
有人知道我怎么做吗?以下是捏合和平移功能。 预先感谢
@objc func pan(sender: UIPanGestureRecognizer) {
if self.isZooming && sender.state == .began {
self.originalImageCenter = sender.view?.center
} else if self.isZooming && sender.state == .changed {
let translation = sender.translation(in: self)
if let view = sender.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
sender.setTranslation(CGPoint.zero, in: self.imageView.superview)
}
}
@objc func pinch(sender:UIPinchGestureRecognizer) {
NotificationCenter.default.post(name: Notification.Name(rawValue: "disablePage"), object: nil)
if sender.state == .began {
let currentScale = self.imageView.frame.size.width / self.imageView.bounds.size.width
let newScale = currentScale*sender.scale
if newScale > 1 {
self.isZooming = true
}
} else if sender.state == .changed {
guard let view = sender.view else {return}
let pinchCenter = CGPoint(x: sender.location(in: view).x - view.bounds.midX,
y: sender.location(in: view).y - view.bounds.midY)
let transform = view.transform.translatedBy(x: pinchCenter.x, y: pinchCenter.y)
.scaledBy(x: sender.scale, y: sender.scale)
.translatedBy(x: -pinchCenter.x, y: -pinchCenter.y)
let currentScale = self.imageView.frame.size.width / self.imageView.bounds.size.width
var newScale = currentScale*sender.scale
if newScale < 1 {
newScale = 1
let transform = CGAffineTransform(scaleX: newScale, y: newScale)
self.imageView.transform = transform
sender.scale = 1
}else {
view.transform = transform
sender.scale = 1
}
} else if sender.state == .ended || sender.state == .failed || sender.state == .cancelled {
guard let center = self.originalImageCenter else {return}
UIView.animate(withDuration: 0.3, animations: {
self.imageView.transform = CGAffineTransform.identity
self.imageView.center = center
}, completion: { _ in
self.isZooming = false
NotificationCenter.default.post(name: Notification.Name(rawValue: "enablePage"), object: nil)
})
}
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}