iOS开发——手势识别器(用手势实现图片旋转和缩小放大)

iOS开发中,除了有关触摸的这组方法来控制用户的手指触控外,还可以用UIGestureRecognize的衍生类来进行判断,方便了开发。
UIGestureRecognize的子类类别有以下几种:

  • UITapGestureRecognizer //轻拍识别器
  • UIPinchGestureRecognizer //捏合识别器
  • UIRotationGestureRecognizer //旋转识别器
  • UISwipeGestureRecognizer //扫动识别器
  • UIPanGestureRecognizer //拖动识别器
  • UILongPressGestureRecognizer //长按识别器

下面的例子我是用UIPinchGestureRecognizer和UIRotationGestureRecognizer通过手势实现图片旋转和缩小放大。

ViewController.m中的代码如下;

#import "ViewController.h"

@interface ViewController ()

@property(nonatomic,strong) UIImageView *imageView;
@property(nonatomic) CGFloat lastRotation;

-(void)changeImageSize:(UIPinchGestureRecognizer *)recognizer;
-(void)rotateImage:(UIRotationGestureRecognizer *)rotateRecognizer;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];

    //在view上添加一个ImageView
    UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Totoro"]];
    image.frame = CGRectMake(0, 0, 128, 128);
    self.imageView = image;
    self.imageView.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2);
    [self.view addSubview:self.imageView];

    //添加捏合手势识别器,changeImageSize:方法实现图片的放大与缩小
    UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(changeImageSize:)];
    [self.view addGestureRecognizer:pinchRecognizer];

    //添加旋转手势识别器,rotateImage:方法实现图片的旋转
    UIRotationGestureRecognizer *rotateRecognizer = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(rotateImage:)];
    [self.view addGestureRecognizer:rotateRecognizer];

}

-(void)changeImageSize:(UIPinchGestureRecognizer *)recognizer
{
    CGRect frame = self.imageView.frame;

    //监听两手指滑动的距离,改变imageView的frame
    frame.size.width = recognizer.scale*128;
    frame.size.height = recognizer.scale*128;
    self.imageView.frame = frame;

    //保证imageView中心不动
    self.imageView.center =CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height/2);
}

-(void)rotateImage:(UIRotationGestureRecognizer *)rotateRecognizer
{
    //改变imageView的角度,使图片旋转
    if ([rotateRecognizer state]==UIGestureRecognizerStateEnded) {
        self.lastRotation = 0.0;
        return;
    }
    CGAffineTransform currentTransform = self.imageView.transform;
    CGFloat rotation = 0.0 - (self.lastRotation - rotateRecognizer.rotation);
    CGAffineTransform newTransform = CGAffineTransformRotate(currentTransform,rotation);
    self.imageView.transform = newTransform;
    self.lastRotation = rotateRecognizer.rotation;
}


@end

运行代码,实现效果如下:

这里写图片描述这里写图片描述

转载于:https://www.cnblogs.com/ahtchxw/p/5466603.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值