最近做了个功能,就是关于打开手机相册取照片,或者是通过相机照相
作为菜鸟的我,花了两天的时间才学会,在此分享给大家
基本思路:
1 打开相机:直接打开,通过代理方法取到我们拍下的照片(在进行照片压缩上传等操作...)
2 打开相册:1)、打开系统预设的相册风格(可使用代理传递选择的照片) 2)、自定义一个相册(样式、打开的是哪个相册、多选等等,这种方法需要自己设置方法传递选择照片,我用的通知)
好,上代码,具体问题在代码里面我再说
!!第一部分:打开相机相册,回调预览
//打开相机 -(void)openCamera { //相机是否访问受限制 if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusRestricted || [ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusDenied) { AccessLimitedViewController *limitedVC = [[AccessLimitedViewController alloc]init]; limitedVC.limiteType =LimiteTypeCamera; [self.navigationController pushViewController:limitedVC animated:YES];//自己定义受限制的界面吧,在此不在添加 return; } if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera; imagePickerController.delegate = self;//设置代理,以便取照片 [self presentViewController:imagePickerController animated:YES completion:NULL]; } else { [PromoteView showPromoteViewWithContent:@"设备不支持摄像功能" andRect:CGRectMake((WIDTH-200)/2, HEIGHT/2-25, 200, 50) andTime:2 andObject:self]; } } //打开相册 这里自定义的相册 - (void)openPhotoLibrary { //相册是否访问受限 if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusRestricted || [ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusDenied) { AccessLimitedViewController *limitedVC = [[AccessLimitedViewController alloc]init]; limitedVC.limiteType = LimiteTypePhtoLibrary; [self.navigationController pushViewController:limitedVC animated:YES];//同上 自己定义该界面吧 return; } [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(photoSelected:) name:@"selectOver" object:nil]; ShowPhotoViewController*photoVc=[[ShowPhotoViewController alloc]init]; photoVc.MaxImageNum=CANSelectNum; photoVc.numberOfSelectedImage=self.selectedImageArray.count; [self.navigationController pushViewController:photoVc animated:YES]; } //回调,收到选择完毕的通知,缓存选择的图片 - (void)photoSelected:(NSNotification*)sender{ [[NSNotificationCenter defaultCenter]removeObserver:self name:@"selectOver" object:nil]; if ([[sender object] isKindOfClass:[NSMutableArray class]]) { NSMutableArray *array=(NSMutableArray*)[sender object]; for (ALAsset *asset in array) { //用于上传 ALAssetRepresentation *representation=asset.defaultRepresentation; CGImageRef imageRef=[representation fullScreenImage]; UIImage *image=[UIImage imageWithCGImage:imageRef]; [self.selectedImageArray addObject:image]; //用于展示 两种图片的效果不一样fullScreenImage、thumbnail UIImage *imageShow=[UIImage imageWithCGImage:asset.thumbnail]; [self.ImageArrayToShow addObject:imageShow]; if (self.ImageArrayToShow.count==CANSelectNum) { openPhotoLibrary.hidden=YES; } } } [self showPhotoSelected]; //开始进行图片压缩、上传 [self loopForUpImage]; } //存储相机拍摄的照片 -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { [picker dismissViewControllerAnimated:YES completion:^{ UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage]; [self.selectedImageArray addObject:image]; [self.ImageArrayToShow addObject:image]; [self showPhotoSelected]; if (self.ImageArrayToShow.count==CANSelectNum) { openPhotoLibrary.hidden=YES; } }]; } //相机的取消按钮 - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker { [self dismissViewControllerAnimated:YES completion:NULL]; } //展示照片 -(void)showPhotoSelected { [showBackView removeFromSuperview]; if (self.ImageArrayToShow.count==0) { return; } showBackView=[[UIView alloc]init]; showBackView.frame=CGRectMake(0, 290, WIDTH, (self.ImageArrayToShow.count/4+1)*(WIDTH-15-20+40)/4); showBackView.backgroundColor=[UIColor yellowColor]; [self.view addSubview:showBackView]; for (int i=0; i<self.ImageArrayToShow.count; i++) { int y=0; int j=i; if (i>3) { j=i-4; y=1; } UIImageView *imageShow=[[UIImageView alloc]init]; imageShow.frame=CGRectMake(10+j*(WIDTH-15)/4, 10+y*(WIDTH-15)/4, (WIDTH-15-20)/4, (WIDTH-15-20)/4); imageShow.image=(UIImage *)self.ImageArrayToShow[i]; imageShow.userInteractionEnabled=YES; [imageShow addSubview:[self createDeleteImageButtonWithTag:i]]; [showBackView addSubview: imageShow]; //添加图片预览 imageShow.userInteractionEnabled=YES; imageShow.tag=i; UITapGestureRecognizer *tapImageToLook=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(lookImage:)]; [imageShow addGestureRecognizer:tapImageToLook]; } } -(UIButton *)createDeleteImageButtonWithTag:(int)tag//删除选定的图片的按钮 { UIButton *button=[[UIButton alloc]init]; button.frame=CGRectMake((WIDTH-15-20)/4-16, -4, 20, 20); button.tag=tag; [button setBackgroundImage:[UIImage imageNamed:@"deleteimage"] forState:UIControlStateNormal]; [button addTarget:self action:@selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside]; return button; } //删除图片 -(void)deleteImage:(UIButton *)sender { NSInteger i=sender.tag; [self.selectedImageArray removeObjectAtIndex:i]; [self.ImageArrayToShow removeObjectAtIndex:i]; [self showPhotoSelected]; openPhotoLibrary.hidden=NO; } //预览图片 -(void)lookImage:(UITapGestureRecognizer *)tap { self.navigationController.navigationBarHidden=YES; //滚动预览 scroolShowAllImage =[[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)]; scroolShowAllImage.contentSize=CGSizeMake(self.selectedImageArray.count*WIDTH, HEIGHT); scroolShowAllImage.backgroundColor=[UIColor blackColor]; scroolShowAllImage.pagingEnabled=YES; [self.view addSubview:scroolShowAllImage]; // 起始图片 NSInteger indexPath=tap.view.tag; scroolShowAllImage.contentOffset=CGPointMake(indexPath*WIDTH, 0); for (int i=0; i<self.selectedImageArray.count; i++) { //尺寸控制 UIImage *image=[[UIImage alloc]init]; image=(UIImage *)self.selectedImageArray[i]; CGFloat imageWidth=image.size.width/2; CGFloat imageHeight=image.size.height/2; CGFloat scale=imageWidth/imageHeight;//比例缩放 if(imageWidth>WIDTH) { imageWidth=WIDTH; imageHeight=imageWidth/scale; } if(imageHeight>HEIGHT) { imageHeight=HEIGHT; imageWidth=imageHeight*scale; } imageView=[[UIImageView alloc]initWithFrame:CGRectMake((WIDTH-imageWidth)/2+WIDTH*i, (HEIGHT-imageHeight)/2, imageWidth, imageHeight)]; imageView.image=image; [scroolShowAllImage addSubview:imageView]; //关闭预览效果 imageView.userInteractionEnabled=YES; UITapGestureRecognizer *tapImageToClose=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeImage)]; [imageView addGestureRecognizer:tapImageToClose]; } } //关闭预览 -(void)closeImage { [imageView removeFromSuperview]; [scroolShowAllImage removeFromSuperview]; self.navigationController.navigationBarHidden=NO; }
上面基本就是打开相册或者相机的方法, 有几个全局变量大家自行设置。另外需要声明代理
<UIImagePickerControllerDelegate,UIActionSheetDelegate>
几个属性 :
@property(nonatomic,strong) NSMutableArray * uploadImageUrl;//存网址
@property(nonatomic,strong)NSMutableArray * selectedImageArray;//存放已选择照片的数组
@property(nonatomic,strong)NSMutableArray * ImageArrayToShow;//存放已选择照片的数组_需要展示的
@property(nonatomic,assign)NSInteger currentUpLoadIndex;//当前上传的第几张
第二部分: 自定义的相册 (相册列表、具体相册)
//获取相册信息 -(void)getPhotoFromALAssetsLibrary { if(self.photoLibrary ==nil){ NSMutableArray * array =[[NSMutableArray alloc]init]; self.photoLibrary =array; } lib = [[ALAssetsLibrary alloc]init]; [lib enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) { if(group != nil){ //这是一个数据模型( 注释在下面) PhotoLibraryDataModel * libraryData = [[PhotoLibraryDataModel alloc]init]; /*<p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(0, 132, 0);">/*!</p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(0, 132, 0);"> <span style="font-variant-ligatures: no-common-ligatures; color: #004c14">@brief</span> <span style="line-height: normal; font-family: 'PingFang SC';">相册名字</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(0, 132, 0);"> */</p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(187, 44, 162);">@property<span style="font-variant-ligatures: no-common-ligatures; color: #000000">(</span>nonatomic<span style="font-variant-ligatures: no-common-ligatures; color: #000000">,</span>strong<span style="font-variant-ligatures: no-common-ligatures; color: #000000">)</span><span style="font-variant-ligatures: no-common-ligatures; color: #703daa">NSString</span><span style="font-variant-ligatures: no-common-ligatures; color: #000000"> *albumName;</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; min-height: 16px;"> </p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; min-height: 16px;"> </p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(0, 132, 0);">/*!</p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(0, 132, 0);"> <span style="font-variant-ligatures: no-common-ligatures; color: #004c14">@brief</span> <span style="line-height: normal; font-family: 'PingFang SC';">相册内照片的数量</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(0, 132, 0);"> */</p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(187, 44, 162);">@property<span style="font-variant-ligatures: no-common-ligatures; color: #000000">(</span>nonatomic<span style="font-variant-ligatures: no-common-ligatures; color: #000000">,</span>assign<span style="font-variant-ligatures: no-common-ligatures; color: #000000">)</span><span style="font-variant-ligatures: no-common-ligatures; color: #703daa">NSInteger</span><span style="font-variant-ligatures: no-common-ligatures; color: #000000"> number;</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(187, 44, 162);">@property<span style="font-variant-ligatures: no-common-ligatures; color: #000000">(</span>nonatomic<span style="font-variant-ligatures: no-common-ligatures; color: #000000">,</span>strong<span style="font-variant-ligatures: no-common-ligatures; color: #000000">)</span><span style="font-variant-ligatures: no-common-ligatures; color: #703daa">ALAssetsGroup</span><span style="font-variant-ligatures: no-common-ligatures; color: #000000"> * group; </span><span style="font-variant-ligatures: no-common-ligatures; color: #008400">//</span><span style="line-height: normal; font-family: 'PingFang SC'; color: rgb(0, 132, 0);">相册对象</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(187, 44, 162);">@property<span style="font-variant-ligatures: no-common-ligatures; color: #000000">(</span>nonatomic<span style="font-variant-ligatures: no-common-ligatures; color: #000000">,</span>assign<span style="font-variant-ligatures: no-common-ligatures; color: #000000">,</span>readwrite<span style="font-variant-ligatures: no-common-ligatures; color: #000000">)</span><span style="font-variant-ligatures: no-common-ligatures; color: #703daa">CGImageRef</span><span style="font-variant-ligatures: no-common-ligatures; color: #000000"> posterImage; </span><span style="font-variant-ligatures: no-common-ligatures; color: #008400">//</span><span style="line-height: normal; font-family: 'PingFang SC'; color: rgb(0, 132, 0);">相册头图</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; line-height: normal; font-family: Menlo; color: rgb(187, 44, 162);">@property<span style="font-variant-ligatures: no-common-ligatures; color: #000000">(</span>nonatomic<span style="font-variant-ligatures: no-common-ligatures; color: #000000">,</span>strong<span style="font-variant-ligatures: no-common-ligatures; color: #000000">)</span><span style="font-variant-ligatures: no-common-ligatures; color: #703daa">NSMutableArray</span><span style="font-variant-ligatures: no-common-ligatures; color: #000000"> * photoArray; </span><span style="font-variant-ligatures: no-common-ligatures; color: #008400">//</span><span style="line-height: normal; font-family: 'PingFang SC'; color: rgb(0, 132, 0);">存放相册组中所有</span><span style="font-variant-ligatures: no-common-ligatures; color: #008400">ALASSet</span></p>*/ NSString * groupName = [group valueForProperty:ALAssetsGroupPropertyName]; libraryData.albumName = groupName; libraryData.posterImage = group.posterImage; NSMutableArray * photoArray = [[NSMutableArray alloc]init]; [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) { if(result!= nil){ NSString * assetType = [result valueForProperty:ALAssetPropertyType]; if([assetType isEqualToString:ALAssetTypePhoto]){ [photoArray addObject:result]; }else if([assetType isEqualToString:ALAssetTypeVideo]){ }else if ([assetType isEqualToString:ALAssetTypeUnknown]){ } } if(index+1 ==group.numberOfAssets){ libraryData.group = group; libraryData.photoArray = photoArray; if ([groupName isEqualToString:@"相机胶卷"]) { [self.photoLibrary insertObject:libraryData atIndex:0]; } else { [self.photoLibrary addObject:libraryData]; } [self creatTableView]; } }]; } } failureBlock:^(NSError *error) { }]; }
//取到照片头图,相册名称 用表格的形式显示出来,有两个参数是我自定义的cell大家忽略即可,只看头图如何取,相册名如取
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; { static NSString* identity=@"cell"; ShowPhotoTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:identity]; if (cell==nil) { cell=[[ShowPhotoTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identity]; } PhotoLibraryDataModel * libraryData = [[PhotoLibraryDataModel alloc]init]; libraryData=(PhotoLibraryDataModel *)[self.photoLibrary objectAtIndex:indexPath.row]; cell.posterImage.image=[UIImage imageWithCGImage:libraryData.group.posterImage];//头图 cell.albumName.text=libraryData.albumName;//相册名 return cell; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath; {//表格的点击事件,传值跳转 PhotoLibraryDataModel * libraryData = [[PhotoLibraryDataModel alloc]init]; libraryData=(PhotoLibraryDataModel *)[self.photoLibrary objectAtIndex:indexPath.row]; PhotoDetailViewController *detail=[[PhotoDetailViewController alloc]init]; detail.MaxImageNum=self.MaxImageNum; detail.numberOfSelectedImage=self.numberOfSelectedImage; detail.albumDataModel=libraryData; [self.navigationController pushViewController:detail animated:YES]; }
接下来就相册详情,可以看到具体的照片,进行选定等操作,代码不上了分享了一下链接,感兴趣自行下载