2013年2月3日 星期日

旋轉手勢辨識


#import <UIKit/UIKit.h>

@interface MyImageView : UIImageView{
    CGPoint startPoint;
    CGAffineTransform currentTransform;
}

@end


#import "MyImageView.h"
#import <QuartzCore/QuartzCore.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];
        */
        /*
        UISwipeGestureRecognizer* swipe1 = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(doLeft:)];
        swipe1.direction = UISwipeGestureRecognizerDirectionLeft;
        //要求雙擊
        swipe1.numberOfTouchesRequired = 2;
        [self addGestureRecognizer:swipe1];
        
        UISwipeGestureRecognizer* swipe2 = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(doRight:)];
        //要求雙擊
        swipe2.numberOfTouchesRequired = 2;
        swipe2.direction = UISwipeGestureRecognizerDirectionRight;
        [self addGestureRecognizer:swipe2];
        */
        
        UIRotationGestureRecognizer* rotation= [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(doRotate:)];
        [self addGestureRecognizer:rotation];
        
    }
    return self;
}

-(void)doRotate:(UIRotationGestureRecognizer*)recognizer{
    //recognizer中取得並旅轉
    self.layer.affineTransform = CGAffineTransformRotate(currentTransform, recognizer.rotation);
}

-(void)doLeft:(UISwipeGestureRecognizer*)recognizer{
    CGPoint newPoint = CGPointMake(self.center.x-50, self.center.y);
    self.center = newPoint;
}
-(void)doRight:(UISwipeGestureRecognizer*)recognizer{
    CGPoint newPoint = CGPointMake(self.center.x+50, self.center.y);
    self.center = newPoint;
}
/*
-(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;
    currentTransform=self.layer.affineTransform;
}



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

@end

沒有留言:

張貼留言