Ios/swift/画像ビューアー
提供: 初心者エンジニアの簡易メモ
画像ビューアーサンプル
画像urlを指定したサンプル
import UIKit import SDWebImage class ImageDetailViewController: UIViewController, UIScrollViewDelegate { @IBOutlet weak var myScrollView: UIScrollView! @IBOutlet weak var myImageView: UIImageView! internal var imgpath: String! = "https://pbs.twimg.com/media/CnHuxaAWAAI0r3y.jpg" override func viewDidLoad() { super.viewDidLoad() print("tarou " + imgpath) if imgpath.containsString("http://") || imgpath.containsString("https://") { let imageURL = NSURL(string: imgpath) myImageView.sd_setImageWithURL(imageURL) } else { myImageView.image = UIImage(named:imgpath) } // 初期scale let myBoundSize: CGSize = UIScreen.mainScreen().bounds.size let zoomScaleWidth:CGFloat = CGFloat(myImageView.bounds.size.width) / CGFloat(myBoundSize.width) let zoomScaleHeight:CGFloat = CGFloat(myImageView.bounds.size.height) / CGFloat(myBoundSize.height) var zoomScale:CGFloat = zoomScaleWidth if zoomScaleWidth < zoomScaleHeight { zoomScale = zoomScaleHeight } self.myScrollView.delegate = self self.myScrollView.minimumZoomScale = 0.1 self.myScrollView.maximumZoomScale = 8 self.myScrollView.scrollEnabled = true self.myScrollView.showsHorizontalScrollIndicator = true self.myScrollView.showsVerticalScrollIndicator = true let doubleTapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self , action:#selector(self.doubleTap(_:))) doubleTapGesture.numberOfTapsRequired = 2 self.myImageView.userInteractionEnabled = true self.myImageView.addGestureRecognizer(doubleTapGesture) self.myScrollView.setZoomScale(zoomScale, animated: false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // ピンチイン・ピンチアウト func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? { return self.myImageView } // ダブルタップ func doubleTap(gesture: UITapGestureRecognizer) -> Void { print(self.myScrollView.zoomScale) if ( self.myScrollView.zoomScale < self.myScrollView.maximumZoomScale ) { let newScale:CGFloat = self.myScrollView.zoomScale * 3 let zoomRect:CGRect = self.zoomRectForScale(newScale, center: gesture.locationInView(gesture.view)) self.myScrollView.zoomToRect(zoomRect, animated: true) } else { self.myScrollView.setZoomScale(1.0, animated: true) } } // 領域 func zoomRectForScale(scale:CGFloat, center: CGPoint) -> CGRect{ var zoomRect: CGRect = CGRect() zoomRect.size.height = self.myScrollView.frame.size.height / scale zoomRect.size.width = self.myScrollView.frame.size.width / scale zoomRect.origin.x = center.x - zoomRect.size.width / 2.0 zoomRect.origin.y = center.y - zoomRect.size.height / 2.0 return zoomRect } }