写入相册需要导入的头文件:
#import
<AssetsLibrary/AssetsLibrary.h>
...
1. iOS7之后的截屏方法,返回view
UIView *view = [self.view
snapshotViewAfterScreenUpdates:YES];
[self.view
addSubview:view];
2. 返回UIImage的截屏方法
/**
* 截屏
*
* @param view 需要截屏的视图
*
* @return 截屏后的图片
*/
- (UIImage *)captureImageInView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRef imageRef = viewImage.CGImage;
CGRect rect = view.bounds; // 在view上的截图的区域
CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);
UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRefRect];
NSData *imageViewData = UIImagePNGRepresentation(sendImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"result.png"];
NSLog(@"%@", savedImagePath);
[imageViewData writeToFile:savedImagePath atomically:YES];
CGImageRelease(imageRefRect);
return viewImage;
* 截屏
*
* @param view 需要截屏的视图
*
* @return 截屏后的图片
*/
- (UIImage *)captureImageInView:(UIView *)view
{
UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGImageRef imageRef = viewImage.CGImage;
CGRect rect = view.bounds; // 在view上的截图的区域
CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);
UIImage *sendImage = [[UIImage alloc] initWithCGImage:imageRefRect];
NSData *imageViewData = UIImagePNGRepresentation(sendImage);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:@"result.png"];
NSLog(@"%@", savedImagePath);
[imageViewData writeToFile:savedImagePath atomically:YES];
CGImageRelease(imageRefRect);
return viewImage;
}
3. 写入相册
//
写入相册
- (void)saveToLibratyWithImage:(UIImage *)image
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:[image CGImage]
orientation:(ALAssetOrientation)[image imageOrientation]
completionBlock:^(NSURL *assetURL, NSError *error){
- (void)saveToLibratyWithImage:(UIImage *)image
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library writeImageToSavedPhotosAlbum:[image CGImage]
orientation:(ALAssetOrientation)[image imageOrientation]
completionBlock:^(NSURL *assetURL, NSError *error){
}];
}
iOSTalk,分享iOS成长之路的点点滴滴。微信扫一扫即可关注。