今回はダブルタップイベントを拾って拡大してみる。
プログラムによる拡大
前回の拡大は基本的に UIScrollView に任せていた。ピンチ操作すると UIScrollViewが勝手に拡大・縮小の動作を行った。今回はダブルタップを検出した後、プログラムで拡大処理を行う必要がある。UIScrollViewにはその為のメソッドが用意されているのでこれを使う。
zoomToRect:animated:
UIScrollView Class Reference
ダブルタップ時の動作
ダブルタップされた時の拡大は標準の写真アプリの様にタップしたポイントを中心にして2倍のズームインとしたい。
また既に拡大されている時にダブルタップした場合は等倍に戻すようにする。
考え方
タップした位置を中心にして拡大したいので今回の用途では -[UIScrollView zoomToRect:animated:]が使えそうだ。このメソッドは拡大したい領域を zoomToRect: で指定する。イメージはこんな感じ。
UIScrollViewの大きさから拡大領域のサイズを計算し、タップ位置から左上の座標を割り出す。
実装
さてこれを実装するわけだが上で述べた考え方ズバリのコードがプログラミングガイドに載っていた。
Scroll View Programming Guide for iOS: Basic Zooming Using the Pinch Gestures より引用。
- (CGRect)zoomRectForScrollView:(UIScrollView *)scrollView withScale:(float)scale withCenter:(CGPoint)center {
CGRect zoomRect;
// The zoom rect is in the content view's coordinates.
// At a zoom scale of 1.0, it would be the size of the
// imageScrollView's bounds.
// As the zoom scale decreases, so more content is visible,
// the size of the rect grows.
zoomRect.size.height = scrollView.frame.size.height / scale;
zoomRect.size.width = scrollView.frame.size.width / scale;
// choose an origin so as to get the right center.
zoomRect.origin.x = center.x - (zoomRect.size.width / 2.0);
zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0);
return zoomRect;
}これを借用して組み込んでみる。
ダブルタップの処理は前回作成した CustomImageView の touchesEnded: に実装する。こんな感じ。
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch* touch = [touches anyObject];
if ([touch tapCount] == 2) {
UIScrollView* scrollView = (UIScrollView*)self.superview;
CGRect zoomRect;
if (scrollView.zoomScale > 1.0) {
zoomRect = scrollView.bounds;
} else {
zoomRect = [self zoomRectForScrollView:scrollView
withScale:2.0
withCenter:[touch locationInView:nil]];
}
[scrollView zoomToRect:zoomRect animated:YES];
}
}すっきり簡単。サンプル実行
さてサンプルを実行してみよう。適当なところをダブルタップする。
拡大された。
もう一度ダブルタップすると等倍表示に戻る。よさそうだ。
ソースコード
GitHubからどうぞ。
EasyGallery at 2010-09-11 from xcatsan's iOS-Sample-Code - GitHub






Responses
Leave a Response