您的位置:首页 > 移动开发 > IOS开发

ios学习笔记——保存图片到相册

2016-06-03 22:06 465 查看
最近项目要用到,这是自己练手的程序

//
//  ViewController.m
//  SJZSaveImage
//
//  Created by mac on 16/6/3.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "ViewController.h"

@interface ViewController () <UIActionSheetDelegate>

@property (nonatomic, strong) UIImage * image;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"保存图片";

UIImage * image = [UIImage imageNamed:@"saveImage.jpg"];
self.image = image;

UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 2)];
imageView.center = self.view.center;
imageView.image = image;

[self.view addSubview:imageView];

[self createButton];
}

- (void)createButton
{
UIButton * button = [[UIButton alloc] initWithFrame:CGRectMake(40, self.view.frame.size.height * 7 / 8, self.view.frame.size.width - 80, 40)];
button.backgroundColor = [UIColor whiteColor];
[button setTitle:@"保存图片" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.layer.cornerRadius = 4.0;
[button addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}

- (void)buttonClick
{
if([[UIDevice currentDevice].systemVersion doubleValue] > 8.0){
//ios8之后用UIAlertController代替UIActionSheet
UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];

//增加保存图片action
UIAlertAction *action = [UIAlertAction actionWithTitle:@"保存图片" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

//将图片保存到相册,回调函数必须为这个形式
UIImageWriteToSavedPhotosAlbum(self.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);

}];

[action setValue:[UIColor blackColor] forKey:@"_titleTextColor"];
[alert addAction:action];

//增加取消action
UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

}];
[actionCancel setValue:[UIColor redColor] forKey:@"_titleTextColor"];
[alert addAction:actionCancel];

[self presentViewController:alert animated:YES completion:nil];
}else{
UIActionSheet * action = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"保存图片" otherButtonTitles:nil, nil];
[action showInView:self.view];
}
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 0){
//将图片保存到相册,该函数的回调必须为这种形式
UIImageWriteToSavedPhotosAlbum(self.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}
}

//保存图片回调函数
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
//我们可以在这里设置弹出框
if(error){
NSLog(@"保存失败");
}else{
NSLog(@"保存成功");
}
}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: