UIViewをタッチイベントで回転させる
今度はタッチイベントで、タッチした後に指を動かしたら画像が回転するように作ってみる。
タッチの移動はtouchesMovedで検知できる。
UIViewに以下のようなコードを実装して、
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
/**
* タッチイベント開始
*/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 最初のタッチ地点を取っておく
lastPoint = [[touches anyObject] locationInView:self.superview];
}
/**
* タッチ移動
*/
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
// タッチされている座標をゲット
CGPoint p = [[touches anyObject] locationInView:self.superview];
// 角度を計算
CGFloat ax = (lastPoint.x - self.center.x);
CGFloat ay = (lastPoint.y - self.center.y);
CGFloat bx = (p.x - self.center.x);
CGFloat by = (p.y - self.center.y);
// ラジアンをゲット
CGFloat r = atan2(ax * by - ay * bx, ax * bx + ay * by);
// アニメーション設定開始
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.05];
// 回転
self.transform = CGAffineTransformRotate(self.transform, r);
// アニメーションをコミット
[UIView commitAnimations];
// 今回の座標が次のイベントの時の起点になるので更新しておく
lastPoint = p;
}
/**
* タッチイベント終了
*/
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
} |
動かした結果がこれ。
今度作ってみるアプリでもViewをタッチで回転する必要がありそうだからもうちょっと調べねば。