IOS实用技术之手势缩放图片

来源:互联网 发布:人工智能研发企业 编辑:程序博客网 时间:2024/05/21 18:44

好久不更博文了,是因为博主最近去给自己充电了哈哈。今天聊一聊如何实现手势缩放的简单效果

为了实现这个效果,我们需要重写UIImageView,同时因为放大的图片超出了屏幕的显示范围,我们还需要添加ScrollView

-(instancetype)initWithFrame:(CGRect)frame{    //1.初始化,添加手势    self = [super initWithFrame:frame];    if(self)    {        self.userInteractionEnabled = YES;        self.contentMode =UIViewContentModeScaleAspectFit;        _totalScale = 1.0;                // 捏合手势缩放图片        UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(zoomImage:)];        [self addGestureRecognizer:pinch];    }    //2.创建大图scrollview    if(self.image.size.height>self.bounds.size.height)    {        if(!_scrol)        {            _scrol = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height)];            [self addSubview:_scrol];            _scrolImageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _scrol.bounds.size.width, _scrol.bounds.size.height)];            [_scrol addSubview:_scrolImageview];            _scrol.backgroundColor = [UIColor whiteColor];            _scrolImageview.contentMode = UIViewContentModeScaleAspectFit;        }    }    _scrol.contentSize = CGSizeMake(0, self.image.size.height);        return self;}

具体实现缩放的方法:手势触发后,在视图上添加滚动视图,再在滚动视图上添加新的UIImageView,随着手势拖动放大或缩小:

//捏合手势放大图片- (void)zoomImage:(UIPinchGestureRecognizer *)recognizer{    if (!_zoomscrol) {        //懒加载,在本视图上加scorellerview        _zoomscrol = [[UIScrollView alloc] initWithFrame:self.bounds];        _zoomscrol.backgroundColor = [UIColor whiteColor];        UIImageView *zoomingImageView = [[UIImageView alloc] initWithImage:self.image];        zoomingImageView.bounds = self.bounds;        zoomingImageView.contentMode = UIViewContentModeScaleAspectFill;        _zoomImageview = zoomingImageView;        [_zoomscrol addSubview:_zoomImageview];        [self addSubview:_zoomscrol];                        _zoomscrol.contentSize = CGSizeMake(zoomingImageView.bounds.size.width * 2, zoomingImageView.bounds.size.height * 1.5);        _zoomscrol.contentInset = UIEdgeInsetsMake(zoomingImageView.bounds.size.height, zoomingImageView.bounds.size.width, 0, 0);    }    CGFloat scale = recognizer.scale;    CGFloat temp = _totalScale + (scale - 1);    [self setTotalScale:temp];    recognizer.scale = 1.0;}

为了防止无限放大造成图片失真影响用户体验度,我们需要给缩放的限度加个约束:

//约束缩放- (void)setTotalScale:(CGFloat)totalScale{    if ((_totalScale < 0.5 && totalScale < _totalScale) || (_totalScale > 2.0 && totalScale > _totalScale)) return; // 最大缩放 2倍,最小0.5倍        _totalScale = totalScale;        _zoomImageview.transform = CGAffineTransformMakeScale(totalScale, totalScale);}

最后,不要忘了添加清除缩放的方法:

// 清除缩放- (void)eliminateScale{    //全部浮空,总缩放倍数设1    [_zoomscrol removeFromSuperview];    _zoomscrol = nil;    _zoomImageview = nil;    _totalScale = 1.0;}


0 0
原创粉丝点击