-(void)buttonAction:(UIButton *)btn
{
//此处我只写了按钮事件,至于button的创建我想只要你已经开始学习iOS了就会的
UIWindow *window = [UIApplication sharedApplication].keyWindow;
UIImage *image = [self snapshot:window/*你要截取的视图*/];
UIImageWriteToSavedPhotosAlbum(image/*你要保存到本地相册的图片对象,当然此处更多的需求可能是长按保存,那你就写个长按收拾UILongPressGestureRecognizer手势,给手势加个触发方法不就行了嘛*/, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
//添加长安手势(如果需求是长按保存图片)
// UILongPressGestureRecognizer *gestur = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
// [self.view addGestureRecognizer:gestur];
}
- (void)longPressAction:(UIGestureRecognizer *)gestrue
{
if (gestrue.state != UIGestureRecognizerStateBegan)
{
//这个if一定要加,因为长按会有好几种状态,按住command键,点击UIGestureRecognizerStateBegan就能看到所有状态的枚举了,因为如果不加这句的话,此方法可能会被执行多次
return;//什么操作都不做,直接跳出此方法
}
//此处执行你想要执行的代码
UIImage *image = [[UIImage alloc] init];/*当然此处需要拿到你需要保存的图片*/
UIImageWriteToSavedPhotosAlbum(image/*你要保存到本地相册的图片对象,当然此处更多的需求可能是长按保存,那你就写个长按收拾UILongPressGestureRecognizer手势,给手势加个触发方法不就行了嘛*/, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
}
- (UIImage *)snapshot:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
NSString *message = @"保存失败";
if (!error) {
message = @"成功保存到相册";
}else
{
message = [error description];
}
NSLog(@"message is %@",message);
}