標籤:
功能如下:
1.點擊頭像,提示選擇更換頭像方式①相簿 ②照相.
2.點擊相簿,實現通過讀取系統相簿,擷取圖片進行替換.
3.點擊照相,通過網路攝影機照相,進行替換照片.
4.如果網路攝影機,彈出框警告.
代碼如下:
1.通過UIActionSheet對象實現提示功能
//建立對象 UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle: @"提示" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相簿",@"拍照", nil]; //在視圖上展示 [actionSheet showInView:self.view]; [actionSheet release];
2.實現相應代理事件,代理UIActionSheetDelegate,方法如下
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex: (NSInteger)buttonIndex { // 相簿 0 拍照 1 switch (buttonIndex) { case 0: //從相簿中讀取 [self readImageFromAlbum]; break; case 1: //拍照 [self readImageFromCamera]; break; default: break; }}3.實現從相簿讀取圖片功能,代碼如下
//從相簿中讀取- (void)readImageFromAlbum { //建立對象 UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; //(選擇類型)表示僅僅從相簿中選取照片 imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //指定代理,因此我們要實現UIImagePickerControllerDelegate, UINavigationControllerDelegate協議 imagePicker.delegate = self; //設定在相簿選完照片後,是否跳到編輯模式進行圖片剪裁。(允許使用者編輯) imagePicker.allowsEditing = YES; //顯示相簿 [self presentViewController:imagePicker animated:YES completion:nil]; [imagePicker release]; }4.實現拍照功能
- (void)readImageFromCamera { if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) { UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init]; imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; imagePicker.delegate = self; imagePicker.allowsEditing = YES; //允許使用者編輯 [self presentViewController:imagePicker animated:YES completion:nil]; [imagePicker release]; } else { //快顯視窗響應點擊事件 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"未檢測到網路攝影機" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"確定", nil]; [alert show]; [alert release]; }}5.圖片完成處理後提交,代理方法UIPickerControllerDelegate
//圖片完成之後處理- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo { //image 就是修改後的照片 //將圖片添加到對應的視圖上 [button setImage:image forState:UIControlStateNormal]; //結束操作 [self dismissViewControllerAnimated:YES completion:nil];}
【學習ios之路:UI系列】點擊更換頭像實現從相簿讀取照片和拍照兩種功能