iOS之点击图片(头像)放大

点击图片和头像放大是一种常见的效果,这里话不多说,现上效果图:
效果图
其实这个效果实现起来很简单,先定义一个黑色的背景视图,将图片放大后的效果放在背景视图上后将背景视图隐藏,再添加点击事件和动画,点击时显示和隐藏即可,代码如下:
#import "ViewController.h"
@interface ViewController ()
//头像
@property (weak, nonatomic) IBOutlet UIImageView *headView;
//黑色背景
@property (strong , nonatomic) UIView *background;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    头像的UIImageView允许用户交互
    self.headView.userInteractionEnabled = YES;
//    初始化背景视图
    self.background = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
//    设置背景视图为黑色
    [self.background setBackgroundColor:[UIColor blackColor]];
//    将背景视图隐藏
    [self.background setAlpha:0];
//    在原始图中加入背景视图
    [self.view addSubview:self.background];
//    初始化图片(放大的图片)
    UIImageView *image = [[UIImageView alloc]initWithImage:self.headView.image];
//    设置图片的x,y,宽,高
    CGFloat x,y,width,heigth;
//    设置x值
    x = 0;
//    根据屏幕的宽度设置图片的宽
    width = [UIScreen mainScreen].bounds.size.width;
//    根据屏幕的宽度及图片的比例设置图片的高
    heigth = self.headView.image.size.height / self.headView.image.size.width * width;
//    设置y值
    y = ([UIScreen mainScreen].bounds.size.height - heigth) / 2;
//    将设置好的x,y,宽,高赋予图片
    [image setFrame:CGRectMake(x, y, width, heigth)];
//    在背景视图中加入图片
    [self.background addSubview:image];
//    建立图片的点击事件
    UIGestureRecognizer *tapImage = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [self.headView addGestureRecognizer:tapImage];
//    建立背景的点击事件
    UIGestureRecognizer *tapBackground = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [self.background addGestureRecognizer:tapBackground];
//
}
#pragma mark 点击方法的动画
- (void)tapAction:(UIGestureRecognizer *)tap{
    [UIView animateWithDuration:0.4 animations:^{
        if (tap.view == self.headView) {
            [self.background setAlpha:1];
        }else
            [self.background setAlpha:0];
    }];
}
@end

SKPreviewer

SKPreviewer是小编自己封装的一个类,支持图片的点击放大,双击放大双击点,手势缩放等功能。
效果图如下:
使用方法也十分简单,导入类,添加一句代码即可。
[SKPreviewer previewFromImageView:sender.imageView container:self.view];
SKPreviewer的Demo下载地址:Demo

希望这篇文章对各位看官有所帮助

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容