实现类似于微信大图查看器的放大缩小功能



 scrollview本身具有放大缩小的功能,我们利用scrollview来实现。创建好scrollview之后,将imageview放到scrollview上

        _scrollview = [[UIScrollViewalloc]initWithFrame:self.frame];

        _scrollview.showsHorizontalScrollIndicator =NO;

        _scrollview.showsVerticalScrollIndicator =NO;

        _scrollview.delegate =self;

        _scrollview.maximumZoomScale =2.f

        _scrollview.minimumZoomScale =.5f;

        _scrollview.contentSize =self.frame.size;

        [self addSubview:_scrollview];

        

        [_scrollviewaddSubview:imageView];


实现scrollview的代理方法

#pragma mark---UIScrollViewDelegate

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView

{

    //只有 scrollviewdelegate复写了viewForZoomingInScrollView scrollview才会缩放。

    return self.imageView;

    

}


Tips:这里是为了保证不管如何缩放,缩放的中心点都是scrollview的中心

- (void)scrollViewDidZoom:(UIScrollView *)scrollView{

    

    CGRect rect = imageView.frame;


    CGFloat x = ((CGRectGetWidth(_scrollview.frame) - (rect.size.width))/2.f);

    CGFloat y = (CGRectGetHeight(_scrollview.frame) - (rect.size.height))/2.f;

    rect.origin.x = x <0?0:x;

    rect.origin.y = y <0?0:y;

    imageView.frame = rect;

    

    

}


- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(nullableUIView *)view atScale:(CGFloat)scale{

    

    if(scale <= 1.f){

        

        [UIViewanimateWithDuration:.3fanimations:^{

            _scrollview.zoomScale =1.0f;

        }];

        

    }

}


另外微信的图片查看器还有一个从小图的位置开始放大的功能,我们通过改变大图做放大缩小动画时候的初始的坐标

来实现它

 核心代码如下:

 convertView是放原小图的view(可能是一个imageView,或者button什么的),我们将这个convertView的坐标转换成当前大图查看器的坐标;imageView就是大图的imageView

        CGRect convertRect = [convertView convertRect:convertView.bounds           toView:self];

        

        CGRect rect = imageView.frame;

        //先转换大图的坐标为小图的位置

        imageView.frame = convertRect;

        [UIView animateWithDuration:.3f animations:^{

            //恢复成大图实际放大的坐标

            imageView.frame = rect;

        }completion:^(BOOL finished){

 

        }];


这样就实现了微信大图查看器炫酷的效果



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值