pragma mark - 通過URL生成二維碼
- (UIImage *) create2DCodeImageWithSize:(CGFloat) size codeUrl:(NSString *) codeUrl{
// 實(shí)例化二維碼濾鏡
CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
// 恢復(fù)濾鏡的默認(rèn)屬性 (因為濾鏡有可能保存上一次的屬性)
[filter setDefaults];
// 將字符串轉(zhuǎn)換成NSdata
NSData *data = [codeUrl dataUsingEncoding:NSUTF8StringEncoding];
// 通過KVO設(shè)置濾鏡, 傳入data, 將來濾鏡就知道要通過傳入的數(shù)據(jù)生成二維碼
[filter setValue:data forKey:@"inputMessage"];
// 生成二維碼
CIImage *outputImage = [filter outputImage];
UIImage *image = [self changeImageSizeWithCIImage:outputImage andSize:size];
return image;
}
pragma mark - 調(diào)整圖片大小
- (UIImage *)changeImageSizeWithCIImage:(CIImage *)ciImage andSize:(CGFloat)size{
CGRect extent = CGRectIntegral(ciImage.extent);
CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
// 創(chuàng)建bitmap;
size_t width = CGRectGetWidth(extent) * scale;
size_t height = CGRectGetHeight(extent) * scale;
CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
CIContext *context = [CIContext contextWithOptions:nil];
CGImageRef bitmapImage = [context createCGImage:ciImage fromRect:extent];
CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
CGContextScaleCTM(bitmapRef, scale, scale);
CGContextDrawImage(bitmapRef, extent, bitmapImage);
// 保存bitmap到圖片
CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
CGContextRelease(bitmapRef);
CGImageRelease(bitmapImage);
return [UIImage imageWithCGImage:scaledImage];
}
pragma mark - 繪制并保存圖片
- (void) clickDownloadButton {
UIGraphicsBeginImageContext(CGSizeMake(640, 910));
UIImage *backImage = [UIImage imageNamed:@"download_pic"];
[backImage drawInRect:CGRectMake(0, 0, 640, 910)];
UIImage *imageface = [self create2DCodeImageWithSize:370 codeUrl:_codeUrl];
[imageface drawInRect:CGRectMake(135, 270, 370, 370)];
UIImage *iconImage = [self makeRoundedImage:_userIconImageView.image radius:50];
[iconImage drawInRect:CGRectMake(70, 126, 100, 100)];
NSString *str1 = _userNameLabel.text;
[str1 drawAtPoint:CGPointMake(200, 136) withAttributes:@{NSForegroundColorAttributeName:RGBCOLOR(37, 182, 237),NSFontAttributeName:[UIFont systemFontOfSize:32]}];
NSString *str2 = _userShopLabel.text;
[str2 drawAtPoint:CGPointMake(200, 186) withAttributes:@{NSForegroundColorAttributeName:RGBCOLOR(69, 69, 69),NSFontAttributeName:[UIFont systemFontOfSize:28]}];
//從當(dāng)前上下文獲取圖片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
//結(jié)束圖像繪制上下文
UIGraphicsEndImageContext();
//保存到相冊
// UIImageWriteToSavedPhotosAlbum(image, self, @selector(bigPicImage:didFinishSavingWithError:contextInfo:), nil);
[self saveImage:image];
}
pragma mark - UIImage切圓角
-(UIImage *) makeRoundedImage:(UIImage *) image
radius: (float) radius;
{
// 截取一部分圖片
CGRect rect = CGRectMake( 0, 0, MIN(image.size.width, image.size.height), MIN(image.size.width, image.size.height));
CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
UIImage *bg = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
CALayer *imageLayer = [CALayer layer];
imageLayer.frame = CGRectMake(0, 0, 2 * radius, 2 * radius);
imageLayer.contentsScale = [[UIScreen mainScreen] scale];
imageLayer.contents = (id) bg.CGImage;
imageLayer.cornerRadius = radius;
imageLayer.masksToBounds = YES;
UIGraphicsBeginImageContext(CGSizeMake(2 * radius, 2 * radius));
[imageLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return roundedImage;
}
- (PHAssetCollection *)collection{
// 先獲得之前創(chuàng)建過的相冊
PHFetchResult <PHAssetCollection *> *collectionResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
for (PHAssetCollection *collection in collectionResult) {
if ([collection.localizedTitle isEqualToString:photosName]) {
return collection;
}
}
// 如果相冊不存在,就創(chuàng)建新的相冊(文件夾)
__block NSString *collectionId = nil; // __block修改block外部的變量的值
// 這個方法會在相冊創(chuàng)建完畢后才會返回
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
// 新建一個PHAssertCollectionChangeRequest對象, 用來創(chuàng)建一個新的相冊
collectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:photosName].placeholderForCreatedAssetCollection.localIdentifier;
} error:nil];
return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionId] options:nil].firstObject;
}
/**
* 返回相冊,避免重復(fù)創(chuàng)建相冊引起不必要的錯誤
*/
- (void)saveImage:(UIImage *) image{
/*
PHAsset : 一個PHAsset對象就代表一個資源文件,比如一張圖片
PHAssetCollection : 一個PHAssetCollection對象就代表一個相冊
*/
__block NSString *assetId = nil;
// 1. 存儲圖片到"相機(jī)膠卷"
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ // 這個block里保存一些"修改"性質(zhì)的代碼
// 新建一個PHAssetCreationRequest對象, 保存圖片到"相機(jī)膠卷"
// 返回PHAsset(圖片)的字符串標(biāo)識
assetId = [PHAssetCreationRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (error) {
NSLog(@"保存圖片到相機(jī)膠卷中失敗");
return;
}
NSLog(@"成功保存圖片到相機(jī)膠卷中");
// 2. 獲得相冊對象
PHAssetCollection *collection = [self collection];
// 3. 將“相機(jī)膠卷”中的圖片添加到新的相冊
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
// 根據(jù)唯一標(biāo)示獲得相片對象
PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil].firstObject;
// 添加圖片到相冊中
[request addAssets:@[asset]];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (error) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[MBProgressHUD ZP_ShowRemindUserText:@"保存到相冊失敗" toView:self.superview inPeriod:1 yOffset:200];
}];
return;
}
// PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil].firstObject;
// [PHAssetCreationRequest deleteAssets:@[asset]];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
[MBProgressHUD ZP_ShowRemindUserText:@"圖片已保存到相冊/掌上好房通" toView:self.superview inPeriod:1 yOffset:200];
}];
}];
}];
}