How to make a photo zoom, setting aspect ratio and

2019-07-31 16:09发布

[After scrolling : Problem White Screen]1

After Zooming

[Before Zoom image setted aspect ratio]

I am implementing a photo view page, which includes just a photo. Functionalities : Zoom.

As the image is of size 1024x510. I have implemented aspect ratio and set the imageview frame to the screensize. I have implemented using Scrollview and imageview concept.

The problem is that, when I zoom the image white screen is also zoomed. Problem is the white space os imageview while zooming. . Code

override func viewDidLoad() {
super.viewDidLoad()



print(imageIndex)
self.scrollV.maximumZoomScale = 5.0
self.scrollV.minimumZoomScale = 1.0
 self.scrollV.contentSize = self.view.bounds.size;
self.scrollV.delegate = self

let urlStr : NSString = vehicleImages[imageIndex].stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!




url=NSURL(string: urlStr as String)
imageView.kf_setImageWithURL(url,placeholderImage: UIImage(named: "placeholder.png"))

}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
    return imageView

}

1条回答
冷血范
2楼-- · 2019-07-31 16:28

Take a look at these methods. May be it will help. I have scroll view stretched to controller's view size. customizeScrollView() will calculate min and max scale options. centerImageView() will put UIImageView in the center of your UIScrollView

fileprivate func customizeScrollView() {
    guard let image = imageView?.image else { return }
    var minZoom = fmin(self.view.frame.width / image.size.width, self.view.frame.height / image.size.height)
    minZoom = fmin(1.0, minZoom)

    scrollView?.contentSize = image.size
    scrollView?.minimumZoomScale = minZoom
    scrollView?.addSubview(self.imageView!)
    scrollView?.setZoomScale(minZoom, animated: false)
    centerImageView()
}

fileprivate func centerImageView() {
    guard let imageView = imageView else { return }
    guard let scrollView = scrollView else { return }

    let boundsSize = scrollView.bounds.size
    var frameToCenter = imageView.frame

    // Center horizontally
    if frameToCenter.size.width < boundsSize.width {
        frameToCenter.origin.x = (boundsSize.width - frameToCenter.size.width) / 2
    } else {
        frameToCenter.origin.x = 0
    }

    // Center vertically
    if frameToCenter.size.height < boundsSize.height {
        frameToCenter.origin.y = (boundsSize.height - frameToCenter.size.height) / 2
    } else {
        frameToCenter.origin.y = 0
    }

    imageView.frame = frameToCenter
}

Also UIScrollViewDelegate methods:

/// `UIScrollViewDelegate` protocol implementation
extension ImagePreviewController: UIScrollViewDelegate {

    public func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }

    public func scrollViewDidZoom(_ scrollView: UIScrollView) {
        centerImageView()
    }
}
查看更多
登录 后发表回答