2013年2月3日 星期日

位移手勢辨識


#import <UIKit/UIKit.h>

@interface MyImageView : UIImageView{
    CGPoint startPoint;
}

@end


#import "MyImageView.h"

@implementation MyImageView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

-(id)initWithCoder:(NSCoder* )aDecoder{
    self = [super initWithCoder:aDecoder];
    if (self) {
        //啟動觸控
        self.userInteractionEnabled= YES;
        //設定圖檔
        self.image = [UIImage imageNamed:@"image4.jpg"];
        //加入手勢
        UIPanGestureRecognizer* pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(doMove:)];
        [self addGestureRecognizer:pan];
    }
    return self;
}

-(void)doMove:(UIPanGestureRecognizer*)recognizer{
    //取得解控點
    CGPoint clickPoint = [recognizer translationInView:self];
    NSLog(@"Move的點是(%.1f,%.1f)",clickPoint.x,clickPoint.y);
    //開始移動
    CGPoint newPoint = CGPointMake(startPoint.x+clickPoint.x, startPoint.y+clickPoint.y);
    self.center = newPoint;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //取得觸控點
    CGPoint clickPoint = [[touches anyObject]locationInView:self];
    NSLog(@"觸控點在(%.1f,%.1f)",clickPoint.x,clickPoint.y);
    startPoint = clickPoint;
}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end

沒有留言:

張貼留言