实现当点击一张图片的时候,图片会放大,再点击图片的背景的时候,图片会缩放回去

时间:2022-04-04 20:34:43

WZStatusPhotoView *iv = [[WZStatusPhotoView alloc] init];

 //添加监听事件

 UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageTap:)];

 [iv addGestureRecognizer:tap];


//当点击图片的触发以下的事件

- (void)imageTap:(UITapGestureRecognizer *)tap

{

    //添加蒙版

    UIView *cover = [[UIView alloc] init];

    cover.alpha = 0.0;

    cover.backgroundColor = [UIColor blackColor];

    cover.frame = [UIScreen mainScreen].bounds;

    //把蒙版添加到Window

    [[UIApplication sharedApplication].keyWindow addSubview:cover];

    // 给蒙板添加监听事件

    UITapGestureRecognizer *coverTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(coverClick:)];

    [cover addGestureRecognizer:coverTap];


    //添加点击的事件到蒙版上

    UIImageView *newIv = [[UIImageView alloc] init];

    // 通过手势获取到点击的图片

    WZStatusPhotoView *photoView =  (WZStatusPhotoView *)tap.view;

    // 从点击的imageview中取出对应的模型数据

    NSURL *url = [NSURL URLWithString:photoView.photo.bmiddle_pic];

    [newIv sd_setImageWithURL:url placeholderImage:[UIImage imageWithName:@"timeline_image_placeholder"]];

    // 坐标系准换, :photoView.frame的坐标系从self(配图容器)的左上角转换为cover的左上角

    newIv.frame = [self convertRect:photoView.frame toView:cover];

    // 记录当前点击viewframe

    self.lastFrame = newIv.frame;

    // 记录缩放的view

    self.customIV = newIv;

    

    [cover addSubview:newIv];

    

    // 缩放点击的图片

    [UIView animateWithDuration:0.25 animations:^{

        

        cover.alpha = 1.0;

        // 设置图片的宽高和位置

        CGRect tempFrame =  newIv.frame;

        tempFrame.size.width = cover.width;

        tempFrame.size.height = tempFrame.size.width * (newIv.image.size.height / newIv.image.size.width);

        tempFrame.origin.x = 0;

        tempFrame.origin.y = (cover.height - tempFrame.size.height) * 0.5;

        newIv.frame = tempFrame;

        

    }];

}


//点击的时候,让图片缩回

- (void)coverClick:(UITapGestureRecognizer *)coverTap

{

    UIView *view =  coverTap.view;

    // 缩小配图

    [UIView animateWithDuration:0.25 animations:^{

        self.customIV.frame = self.lastFrame;

        view.alpha = 0.0;

    } completion:^(BOOL finished) {

        [view removeFromSuperview];

        self.customIV = nil;

    }];

}