ios开发图片点击放大

时间:2023-03-09 05:58:05
ios开发图片点击放大

图片点击放大,再次点击返回原视图.完美封装,一个类一句代码即可调用.IOS完美实现

创建了一个专门用于放大图片的类,以下为.h文件

  1. #import <Foundation/Foundation.h>
  2. @interface SJAvatarBrowser : NSObject
  3. /**
  4. *  @brief  浏览头像
  5. *
  6. *  @param  oldImageView    头像所在的imageView
  7. */
  8. +(void)showImage:(UIImageView*)avatarImageView;
  9. @end

以下为.m文件

  1. #import "SJAvatarBrowser.h"
  2. static CGRect oldframe;
  3. @implementation SJAvatarBrowser
  4. +(void)showImage:(UIImageView *)avatarImageView{
  5. UIImage *image=avatarImageView.image;
  6. UIWindow *window=[UIApplication sharedApplication].keyWindow;
  7. UIView *backgroundView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
  8. oldframe=[avatarImageView convertRect:avatarImageView.bounds toView:window];
  9. backgroundView.backgroundColor=[UIColor blackColor];
  10. backgroundView.alpha=0;
  11. UIImageView *imageView=[[UIImageView alloc]initWithFrame:oldframe];
  12. imageView.image=image;
  13. imageView.tag=1;
  14. [backgroundView addSubview:imageView];
  15. [window addSubview:backgroundView];
  16. UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideImage:)];
  17. [backgroundView addGestureRecognizer: tap];
  18. [UIView animateWithDuration:0.3 animations:^{
  19. imageView.frame=CGRectMake(0,([UIScreen mainScreen].bounds.size.height-image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width)/2, [UIScreen mainScreen].bounds.size.width, image.size.height*[UIScreen mainScreen].bounds.size.width/image.size.width);
  20. backgroundView.alpha=1;
  21. } completion:^(BOOL finished) {
  22. }];
  23. }
  24. +(void)hideImage:(UITapGestureRecognizer*)tap{
  25. UIView *backgroundView=tap.view;
  26. UIImageView *imageView=(UIImageView*)[tap.view viewWithTag:1];
  27. [UIView animateWithDuration:0.3 animations:^{
  28. imageView.frame=oldframe;
  29. backgroundView.alpha=0;
  30. } completion:^(BOOL finished) {
  31. [backgroundView removeFromSuperview];
  32. }];
  33. }
  34. @end

引入此类之后,为自己需要放大的imageView添加tap手势

  1. UITapGestureRecognizer *tap  = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(magnifyImage)];
  2. [self.imageView addGestureRecognizer:tap];
  1. - (void)magnifyImage
  2. {
  3. NSLog(@"局部放大");
  4. [SJAvatarBrowser showImage:self.imageView];//调用方法
  5. }

转载请声明源地址http://blog.****.net/u013082522/article/details/18445901