天天看點

瘋狂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:)];

[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);

imageRotatedByRadians:currentRotation + rotation];

// 如果旋轉手勢結束

if(gesture.state ==UIGestureRecognizerStateEnded)

currentRotation = currentRotation + rotation;

@end

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

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

<a href="http://s3.51cto.com/wyfs02/M00/23/35/wKioL1M1CtLDYhdOAACGbjdrglw629.jpg" target="_blank"></a>

圖1.5 使用旋轉手勢旋轉圖檔

繼續閱讀