我在UIScrollView
中放置了一个UIImageView
。最终目标是在UIScrollView
的范围内旋转、平移和缩放图片。平移和缩放效果很好。旋转最初也能成功,但当完成一次旋转后紧接着进行一次捏合缩放时,图像旋转会重置为0,而图像则被移出了UIScrollView
。
请问有什么建议吗?
@IBOutlet weak var innerScrollView: UIScrollView!
private weak var innerImageView: UIImageView?
var beforeImage: UIImage?
// MARK: -
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
innerScrollView.delegate = self
configureScrollView(innerScrollView, image: beforeImage)
let recognizer = UIRotationGestureRecognizer(target: self, action: "rotateRecognizer:")
if let imageView = innerImageView {
imageView.addGestureRecognizer(recognizer)
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
resetScrollView(innerScrollView)
}
// MARK: -
// MARK: Private Helpers
private func resetScrollView(scrollView: UIScrollView) {
let scaleWidth = scrollView.frame.size.width / scrollView.contentSize.width
let scaleHeight = scrollView.frame.size.height / scrollView.contentSize.height
let minScale = min(scaleHeight, scaleWidth)
scrollView.minimumZoomScale = minScale
scrollView.maximumZoomScale = 1.0
scrollView.zoomScale = minScale
centerScrollViewContents()
}
private func configureScrollView(scrollView: UIScrollView, image: UIImage?) {
guard let img = image else {
return
}
let imageView = UIImageView(image: image)
imageView.userInteractionEnabled = true
imageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: img.size)
scrollView.addSubview(imageView)
scrollView.contentSize = img.size
innerImageView = imageView
}
private func centerScrollViewContents() {
let boundsSize = innerScrollView.bounds.size
var contentsFrame = innerImageView!.frame
if contentsFrame.size.width < boundsSize.width {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0
} else {
contentsFrame.origin.x = 0.0
}
if contentsFrame.size.height < boundsSize.height {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0
} else {
contentsFrame.origin.y = 0.0
}
innerImageView!.frame = contentsFrame
}
func rotateRecognizer(recognizer: UIRotationGestureRecognizer) {
print("The content Offset is \(innerScrollView.contentOffset)")
guard let recView = recognizer.view else {
return
}
recView.transform = CGAffineTransformRotate(recView.transform, recognizer.rotation);
recognizer.rotation = 0;
}
// MARK: -
// MARK: UIGestureRecognizer Delegate Protocol
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
if let imageView = scrollView.subviews.first as? UIImageView {
return imageView
}
return nil
}