LoginSignup
64
65

More than 5 years have passed since last update.

画像をダブルタップとピンチイン・ピンチアウトで拡大・縮小する

Posted at

アプリ画像

アプリ内容

  • 拡大・縮小の範囲は8倍〜1倍
  • ダブルタップ時は3倍ずつ拡大して、上限を超えたら1倍に戻る。

このサンプル画像めっちゃ面白い。
「詳細! Objective-C iPhoneアプリ開発 入門ノート」という書籍のChapter6-4のサンプルアプリをSwiftにしました。そこで使われている画像です。

コード

ViewController.swift
class ViewController: UIViewController , UIScrollViewDelegate{

    @IBOutlet var myImageView: UIImageView!
    @IBOutlet var myScrollView: UIScrollView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // スクロールビューの設定
        self.myScrollView.delegate = self
        self.myScrollView.minimumZoomScale = 1
        self.myScrollView.maximumZoomScale = 8
        self.myScrollView.scrollEnabled = true
        self.myScrollView.showsHorizontalScrollIndicator = true
        self.myScrollView.showsVerticalScrollIndicator = true

        var doubleTapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self
            , action:"doubleTap:")
        doubleTapGesture.numberOfTapsRequired = 2
        self.myImageView.userInteractionEnabled = true
        self.myImageView.addGestureRecognizer(doubleTapGesture)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // ピンチイン・ピンチアウト
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        print("pinch")
        return self.myImageView
    }
    // ダブルタップ
    func doubleTap(gesture: UITapGestureRecognizer) -> Void {

        print(self.myScrollView.zoomScale)
        if ( self.myScrollView.zoomScale < self.myScrollView.maximumZoomScale ) {

            var newScale:CGFloat = self.myScrollView.zoomScale * 3
            var 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
    }
}

ソースアップ

コメント

64
65
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
64
65