LoginSignup
5
5

More than 5 years have passed since last update.

Swift3で9時を起点に時計をドラッグで回転させる

Last updated at Posted at 2017-06-02

時計の針がちょうど9時を起点にUIViewをドラッグで回転させてみます。回転の肝になってるところは atan2(target.y-position.y, target.x-position.x)この部分です。atan2で座標から角度を割り出しています。

imageroteai.gif

実装

var myView: UIView!
    override func viewDidLoad() {
        super.viewDidLoad()
        myView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
        myView.center = self.view.center
        myView.backgroundColor = UIColor.red;        self.view.addSubview(myView)
        myView.layer.anchorPoint = CGPoint(x: 1.0, y: 0.5)

        let box = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        box.backgroundColor = UIColor.blue
        myView.addSubview(box)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent!) {

        let touch = touches.first!
        if touch.view === myView.subviews[0] {
            let position = touch.location(in: self.view)
            let target = myView.center
            let angle = atan2(target.y-position.y, target.x-position.x)
            myView.transform = CGAffineTransform(rotationAngle: angle)
        }

説明

UIViewをインスタンス化する

var myView: UIView!

UIViewの実態を作って描画する


//横幅100の縦幅20のUIView
myView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 20))    //viewの真ん中に配置する
        myView.center = self.view.center
        //UIViewの全体の背景色を赤色に指定する
        myView.backgroundColor = UIColor.red;   
        //画面に描画する
        self.view.addSubview(myView)
        //anchorPointに関して下記参照
        //要は(x: 1.0, y: 0.5)にすることで
        //UIViewの最下部を原点に回転させることができる
        //これを(x: 0.5, y: 0.5)とかにするとブーメランみたいに回ってしまう
        myView.layer.anchorPoint = CGPoint(x: 1.0, y: 0.5)

        //青い部分
        let box = UIView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        box.backgroundColor = UIColor.blue
        myView.addSubview(box)

ドラッグ処理を実装

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent!) {
        //タッチイベント取得
        let touch = touches.first!
        //青い部分をタッチしたときだけ回転させることができる
        if touch.view === myView.subviews[0] {
            //自分の場所を取得して
            let position = touch.location(in: self.view)
            //真ん中を取得して
            let target = myView.center
            //中心点から自分xと自分yを引き算
            let angle = atan2(target.y-position.y, target.x-position.x)
           //transformで回転処理を実行する
            myView.transform = CGAffineTransform(rotationAngle: angle)
        }

参考

anchorPointに関しては下記参照

How to rotate an UIImageView using TouchesMoved

Swift3で時計を回すようにドラッグでクルクル回転させてみる

5
5
0

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
5
5