2012年8月5日日曜日

タッチした座標に画像を移動させる

タッチイベントに関して少し調べたのでメモで。今回はタッチしたところに画像を移動させた際の覚え書きです。

タッチイベントに関しては以下に簡単にまとめられています。

Objective-C講習/タッチイベントについて - 福井高専IT研究会OfficialWiki

開発環境、プロジェクト

開発環境は、Xcode4.3.3、エミュレータはiPhone iOS5.1です。プロジェクトは「Single View Application」を選択。

移動させてみる

ViewController.h

#import 

@interface ViewController : UIViewController{
    UIImageView *_iv;
}

@end

ViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 画像の生成
    UIImage *image = [UIImage imageNamed:@"img1.png"];
    //UIImageViewに画像を乗せる
    _iv = [[UIImageView alloc] initWithImage:image];
    //分かりやすく背景追加
    _iv.backgroundColor = [UIColor whiteColor];
    //UIImageViewの位置とサイズを指定
    [_iv setFrame:CGRectMake(50.0, 50.0, image.size.width, image.size.height)];
    //ビューに表示
    [self.view addSubview:_iv];
}

//タッチされたときに呼ばれるメソッド
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    //タッチイベントを取り出す
    UITouch *touch = [touches anyObject];
    //タッチイベントから座標を取得
    CGPoint point = [touch locationInView:self.view];
    //画像(UIImageView)の中心座標とタッチイベントから取得した座標を同期
    _iv.center = point;
}

実行すると、タッチした座標に画像の中心がくるように移動します。

また、touchesBegan:withEvent:メソッドを以下のようにすると画像の左上隅がタッチした座標に移動するようになります。
- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView:self.view];
    //UIImageViewの大きさのオブジェクトを生成
    CGRect rect = [_iv frame];
    //生成したオブジェクトのx座標をタッチしたx座標にする
    rect.origin.x = point.x;
    //生成したオブジェクトのy座標をタッチしたy座標にする
    rect.origin.y = point.y;
    //座標を同期
    _iv.frame = rect;
}

CGPointで取得した座標を、画像の座標に入れ替えて表示しています。

動作デモ



今回のソース

準備中

参考記事

[iPhone]タッチイベントを検出する - Share Technical Blogs
ドラックで画像を動かす。- iPhoneソースコードがきたなくて

0 件のコメント:

コメントを投稿