Explorer
Explorer

Reputation: 75

How to fullscreen image and dismiss with swipe similar to Apple Photos

How can I implement the fullscreen image and dismiss image functionality of the Apple Photos? Additionally, how can I get the aspect ratio of an image to fit within a fullscreen view? Are they sending a UIImage to a new view controller?

My current method of fullscreening an image simply sets a UIImageView's frame equal to the superview's frame while turning the alphas of the UINavigationBar and UITabBar to 0. And to dismiss, I added a tap gesture recognizer that reverses the alphas and removes the UIImageView from the superview.

Here's my fullscreen and dismiss code

func fullscreen(forImage image: UIImage) {
    let imageView = UIImageView(image: image)
    imageView.frame = self.view.frame
    imageView.backgroundColor = .black
    imageView.contentMode = .scaleAspectFill
    imageView.clipsToBounds = true
    imageView.isUserInteractionEnabled = true

    self.navigationController?.navigationBar.alpha = 0
    self.tabBarController?.tabBar.alpha = 0

    let dismissTap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage))
    imageView.addGestureRecognizer(dismissTap)

    self.view.addSubview(imageView)
}

@objc func dismissFullscreenImage(_ sender: UITapGestureRecognizer) {
    sender.view?.removeFromSuperview()
    self.navigationController?.navigationBar.alpha = 1
    self.tabBarController?.tabBar.alpha = 1
}

Upvotes: 0

Views: 1733

Answers (1)

F22lightning
F22lightning

Reputation: 640

This could easily be achieved using Apple's QuickLook framework as it works great for many extensions and collections of images.

Edit: Most of the functionality you want is built into the QLPreviewController

let previewController = QLPreviewController()
previewController.dataSource = self
self.present(previewController, animated: true, completion: nil)

The data source is whatever class conforms to the QLPreviewControllerDataSource protocol

Here is a video guide from apple on how to achieve this easily

Edit: This part goes in the previewItemAt function

guard let url = Bundle.main.url(forResource: "imageName", withExtension: "jpg")
     else {
        fatalError("Could not load imageName.jpg")
     }

return url as QLPreviewItem

Upvotes: 4

Related Questions