ios 点击放大图片,保存至手机相册

时间:2023-03-09 07:30:42
ios  点击放大图片,保存至手机相册

直接贴.m文件代码

#import "UIImageView+Scale.h"

static CGRect oldframe;

@implementation UIImageView (Scale)

//放大

-(void)showImageView:(UIImageView *)targetImgView {

UIImage *image = targetImgView.image;

UIWindow *window = [UIApplication sharedApplication].keyWindow;

UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];

oldframe =[targetImgView convertRect:targetImgView.bounds toView:window];

bgView.backgroundColor = [UIColor lightGrayColor];

bgView.alpha = 0;

UIImageView *imageView = [[UIImageView alloc ] initWithFrame:oldframe];

imageView.image = image;

imageView.tag = 1001;

[bgView addSubview:imageView];

[window addSubview:bgView];

bgView.userInteractionEnabled = YES;

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

[bgView addGestureRecognizer:tap];

//如果图片还没有加载出来会卡在这里

if (image) {

[UIView animateWithDuration:0.3 animations:^{

imageView.frame = CGRectMake(0,  (SCREEN_HEIGHT - image.size.height * SCREEN_WIDTH / image.size.width)/2, SCREEN_WIDTH, image.size.height * SCREEN_WIDTH/image.size.width);

bgView.alpha = 1;

}];

}

UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(bgView.right - 80, imageView.bottom + 10, 80, 30)];

[btn setTitle:@"保存" forState:0];

[bgView addSubview:btn];

[btn addTarget:self action:@selector(saveImage:) forControlEvents:UIControlEventTouchUpInside];

}

//缩小隐藏

- (void)hideImage:(UITapGestureRecognizer *)tap {

UIView *backgroundView=tap.view;

UIImageView *imageView=(UIImageView*)[tap.view viewWithTag:1001];

[UIView animateWithDuration:0.5 animations:^{

imageView.frame = oldframe;

backgroundView.alpha=0;

} completion:^(BOOL finished) {

[backgroundView removeAllSubviews];

[backgroundView removeFromSuperview];

}];

}

//保存

- (void)saveImage:(UIButton *)sender {

UIImageView *imageView = (UIImageView *)[sender.superview viewWithTag:1001];

UIImage *image = imageView.image;

UIImageWriteToSavedPhotosAlbum(image,self,@selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:),nil);

}

//保存回调

- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {

NSString *message;

if (!error) {

message = @"成功保存到相册~";

}else {

message = [error description];

}

NSLog(@"message is %@",message);

[MBProgressHUD showHUD:message];

}

@end