画像をドラッグさせる Swift3

 

環境

-xcode8
-swift3

実行

on.gif

実装

import UIKit

let imageView = UIImageView()
var preDx : CGFloat!
var preDy : CGFloat!


class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()



//        let topImage:UIImage = UIImage(named:"topImage")!
//        let bottomImage:UIImage = UIImage(named: "bottomImage")!
//        let newSize = CGSize(width:bottomImage.size.width, height:bottomImage.size.height)
//        UIGraphicsBeginImageContextWithOptions(newSize, false, bottomImage.scale)
//        bottomImage.draw(in: CGRect(x:0,y:0,width:newSize.width,height:newSize.height))
//        topImage.draw(in: CGRect(x:0,y:0,width:newSize.width,height:newSize.height),blendMode:CGBlendMode.normal, alpha:1.0)
//        let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()!
//        UIGraphicsEndImageContext()




        let screenWidth:CGFloat = view.frame.size.width
        let screenHeight:CGFloat = view.frame.size.height

        //画像をイメージに追加
        imageView.image = UIImage(named:"topImage")!
        let newRect = CGRect(x:0, y:0, width:200, height:200)
        imageView.frame = newRect
        imageView.center = CGPoint(x:screenWidth/2, y:screenHeight/2)
        self.view.addSubview(imageView)
        imageView.isUserInteractionEnabled = true


        let panGestureRecognizer06 = UIPanGestureRecognizer(target: self, action: #selector(panGesture06(sender:)))
        imageView.addGestureRecognizer(panGestureRecognizer06)

    }


    func panGesture06(sender:UIPanGestureRecognizer) {

        if sender.state == UIGestureRecognizerState.began {
            preDx = imageView.frame.origin.x
            preDy = imageView.frame.origin.y
        }
        let point: CGPoint = sender.translation(in: self.view)
        let movedPoint: CGPoint = CGPoint(x: sender.view!.center.x + point.x, y: sender.view!.center.y + point.y)
//      print(movedPoint)
        sender.view!.center = movedPoint
        sender.setTranslation(CGPoint.zero, in: self.view)
    }



    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

ソース

github

藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

ホーム