接下来讲一下旋转(UIRotationGestureRecognizer)和长按(UILongPressGestureRecognizer)
一,旋转(UIRotationGestureRecognizer)
- (void)addImageViewAndAddRotationGesture
{
// 获取图片路径
NSString *path =[[NSBundle mainBundle] pathForResource:@"image"ofType:@"jpg"];
// 获得图片视图
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:path]];
// 设置 frame,大小和坐标
[imageView setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
// 用户交互开启,默认是关闭,在关闭状态下图片不能点击
[imageView setUserInteractionEnabled:YES];
// 新建旋转手势,初始化方法中设置 target和 action
UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationGestureAction:)];
// 给imageView添加手势
[imageView addGestureRecognizer:rotationGesture];
// release
[rotationGesture release];
// 添加图片
[self.view addSubview:imageView];
[imageView release];
}
两点触摸屏幕旋转时执行rotationGestureAction:
iOS模拟器上按住alt(option)键就可以两点触摸屏幕
- (void)rotationGestureAction:(UIRotationGestureRecognizer *)rotationGesture
{
// 获取当前手势下的视图(返回值是UIView,所以需要强制类型转换)
UIImageView *imageView = (UIImageView *)rotationGesture.view;
// 修改 imageView的 transform属性可以对图片进行线性变换(其实是矩阵变换,一个3 * 3的矩阵,有兴趣的可以看看)
// 用系统的函数来完成旋转,第一个参数是 imageView的 transform,第二个参数是旋转的弧度(角度的另一种表达方式)
imageView.transform = CGAffineTransformRotate(imageView.transform, rotationGesture.rotation);
// 每次旋转完事都得初始化一下 rotation,至于为什么,自己试试就知道效果了
rotationGesture.rotation = 0;
}
二,(UILongPressGestureRecognizer)
- (void)addImageViewAndAddLongPressGesture
{
// 获取图片路径
NSString *path =[[NSBundle mainBundle] pathForResource:@"image"ofType:@"jpg"];
// 获得图片视图
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:path]];
// 设置 frame,大小和坐标
[imageView setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
// 用户交互开启,默认是关闭,在关闭状态下图片不能点击
[imageView setUserInteractionEnabled:YES];
// 新建长按手势,初始化方法中设置 target和 action
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressGestureAction:)];
// 给imageView添加手势
[imageView addGestureRecognizer:longPressGesture];
// release
[longPressGesture release];
// 添加图片
[self.view addSubview:imageView];
[imageView release];
}
长按图片时执行longPressGestureAction:
- (void)longPressGestureAction:(UILongPressGestureRecognizer *)longPressGesture
{
// 获取当前手势下的视图(返回值是UIView,所以需要强制类型转换)
UIImageView *imageView = (UIImageView *)longPressGesture.view;
}
以上是我要说的旋转手势(rotationGesture)和长按手势(longPressGesture)