瘋狂ios講義之實例:通過旋轉手勢旋轉圖片

實例:通過旋轉手勢旋轉圖片

本實例將會對前面的實例進行改進,在前面實例的基礎上增加一個旋轉手勢處理器,從而讓該應用既可根據用戶捏合手勢對圖片進行縮放,也可根據用戶旋轉手勢對圖片進行旋轉。

複製上面的應用,並將該應用改名爲RotateImage。該應用的其他部分基本無須修改,只要把控制器類的實現部分稍作修改,爲UIImageView控件增加旋轉手勢處理器,並讓程序根據手勢旋轉的弧度對圖片進行旋轉即可。下面是修改後的控制器類的實現代碼。

程序清單:codes/01/1.3/RotateImage/RotateImage/FKViewController.m

@implementation FKViewController

UIImage* srcImage;

CGFloat currentScale;

CGFloat currentRotation;

- (void)viewDidLoad

{

[superviewDidLoad];

[UIApplication sharedApplication].statusBarHidden = YES;

srcImage= [UIImage imageNamed:@"seashore.png"];

// 設置圖片直接顯示在中間(不進行任何縮放)

self.view.contentMode = UIViewContentModeCenter;

// 設置imageView初始顯示的圖片

self.imageView.image = srcImage;

// 設置初始的縮放比例

currentScale = 1;

currentRotation = 0;

// 設置imageView允許用戶交互,支持多點觸碰

self.imageView.userInteractionEnabled = YES;

self.imageView.multipleTouchEnabled = YES;

// 創建UIPinchGestureRecognizer手勢處理器,該手勢處理器激發scaleImage:方法

UIPinchGestureRecognizer* gesture = [[UIPinchGestureRecognizer alloc]

initWithTarget:self action:@selector(scaleImage:)];

// imageView添加手勢處理器

[self.imageView addGestureRecognizer:gesture];

// 創建UIRotationGestureRecognizer手勢處理器,該手勢處理器激發rotateImage:方法

UIRotationGestureRecognizer* rotateGesture=

[[UIRotationGestureRecognizer alloc]

initWithTarget:selfaction:@selector(rotateImage:)];

// imageView添加手勢處理器

[self.imageViewaddGestureRecognizer:rotateGesture];

}

- (void)scaleImage:(UIPinchGestureRecognizer*)gesture

{

CGFloatscale = gesture.scale;

// 根據手勢處理器的縮放比例計算縮放後的目標圖片大小

CGSizetargetSize = CGSizeMake(srcImage.size.width * scale * currentScale,

srcImage.size.height * scale * currentScale);

// 對圖片進行縮放、旋轉

self.imageView.image = [[srcImage imageByScalingToSize:targetSize]

imageRotatedByRadians:currentRotation];

// 如果手勢結束

if(gesture.state == UIGestureRecognizerStateEnded)

{

// 計算結束時圖片的縮放比例

currentScale = scale * currentScale;

}

}

- (void)rotateImage:(UIRotationGestureRecognizer*)gesture

{

// 獲取手勢旋轉的弧度

CGFloatrotation = gesture.rotation;

// 根據當前縮放比例計算縮放後的目標圖片大小

CGSizetargetSize = CGSizeMake(srcImage.size.width * currentScale,

srcImage.size.height * currentScale);

// 對圖片進行縮放、旋轉

self.imageView.image = [[srcImage imageByScalingToSize:targetSize]

imageRotatedByRadians:currentRotation + rotation];

// 如果旋轉手勢結束

if(gesture.state ==UIGestureRecognizerStateEnded)

{

currentRotation = currentRotation + rotation;

}

}

@end

上面程序中粗體字代碼爲UIImageView控件增加了一個UIRotationGestureRecognizer手勢處理器,該手勢處理器檢測到旋轉手勢後將會激發該控制器的rotateImage:方法,該方法將會根據手勢旋轉的弧度對圖片進行旋轉(程序同樣使用了UIImage+FKCategory的方法來旋轉圖片)。

編譯、運行該程序,即可看到如圖1.5所示的效果。

wKioL1M1CtLDYhdOAACGbjdrglw629.jpg

1.5 使用旋轉手勢旋轉圖片


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章