Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ImageCropViewController: UIViewController, UIScrollViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
- @IBOutlet var scrollView: UIScrollView?
- var avatarImage: UIImage?
- var avatarImageFrame: CGRect?
- var imageView = UIImageView()
- @IBOutlet var scrollViewHeightConstraint: NSLayoutConstraint!
- @IBOutlet var scrollViewTopConstraint: NSLayoutConstraint!
- override func viewDidLoad() {
- super.viewDidLoad()
- scrollView!.delegate = self
- imageView.frame = CGRectMake(0, 0, (scrollView?.frame.width)!, (scrollView?.frame.height)!)
- if let validImage = self.avatarImage {
- self.imageView.image = validImage
- imageView.contentMode = .Center
- imageView.frame = avatarImageFrame!
- }
- imageView.userInteractionEnabled = true
- scrollView?.addSubview(imageView)
- scrollView?.contentSize = (avatarImage?.size)!
- let scrollViewFrame = scrollView?.frame
- let scaleWidth = (scrollViewFrame?.size.width)! / (scrollView?.contentSize.width)!
- let scaleHeight = (scrollViewFrame?.size.height)! / (scrollView?.contentSize.height)!
- let minScale = min(scaleHeight, scaleWidth)
- scrollView?.minimumZoomScale = minScale
- scrollView?.maximumZoomScale = 1
- scrollView?.zoomScale = minScale
- centerScrollViewContents()
- }
- func centerScrollViewContents() {
- let boundsSize = scrollView?.bounds.size
- var contentsFrame = imageView.frame
- if contentsFrame.size.width < boundsSize?.width {
- contentsFrame.origin.x = ((boundsSize?.width)! - contentsFrame.size.width) / 2
- } else {
- contentsFrame.origin.x = 0
- }
- if contentsFrame.size.height < boundsSize?.height {
- contentsFrame.origin.y = ((boundsSize?.height)! - contentsFrame.size.height) / 2
- } else {
- contentsFrame.origin.y = 0
- }
- imageView.frame = contentsFrame
- }
- func scrollViewDidZoom(scrollView: UIScrollView) {
- centerScrollViewContents()
- }
- func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
- return imageView
- }
- @IBAction func cropTheImage(sender: AnyObject) {
- UIGraphicsBeginImageContextWithOptions((scrollView?.bounds.size)!, true, UIScreen.mainScreen().scale)
- let offset = scrollView?.contentOffset
- CGContextTranslateCTM(UIGraphicsGetCurrentContext(), -(offset?.x)!, -offset!.y)
- scrollView!.layer.renderInContext(UIGraphicsGetCurrentContext()!)
- let image = UIGraphicsGetImageFromCurrentImageContext()
- UIGraphicsEndImageContext()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement