本文讲述使用3.0的方法怎样从iPhone的照片库或照相机获取图像。

我们将创建一个应用程序从图片库或照相机获取图像并显示与屏幕之上。下面是截图:

photo 2

1. 创建一个新的 View Based 程序

我将其命名为 photoApp

 

2. 创建IBOutlet 和 IBAction

打开 photoAppViewController.h 加入下面代码:

#import 
 
@interface PhotoAppViewController : UIViewController
    < UIImagePickerControllerDelegate, UINavigationControllerDelegate > {
	UIImageView * imageView;
	UIButton * choosePhotoBtn;
	UIButton * takePhotoBtn;
}
 
@property (nonatomic, retain) IBOutlet UIImageView * imageView;
@property (nonatomic, retain) IBOutlet UIButton * choosePhotoBtn;
@property (nonatomic, retain) IBOutlet UIButton * takePhotoBtn;
 
-(IBAction) getPhoto:(id) sender;
 
@end

注意我们实现了 UIImagePickerControlDelegate 和 UINavigationControllerDelegate 协议。为了与图像拾取器正确地接口,这两者都是必需的。其余部分应该很简单。我们设定了要使用按钮的IBOutlet以及按下这些按钮时被调用的IBAction。getPhoto方法将显示图像拾取器。

 

3. 创建接口

在Interface Builder中打开photoAppViewController.xib 并遵循下面步骤:

  1. 将 UIImageView 拖入main view
  2. 在Attribute inspector(属性检查器)中将 UIImageView 的 Mode (模式) 设置为 Aspect Fit
  3. 将 UIButton 拖入view 中并命名为 Choose Photo (选取照片)
  4. 将另一个 UIButton 拖入view 中并命名为 Take Photo (照相)

接口看上去像这样:

screenshot_01

4. 连接IBoutlets 和 IBAction

  1. 将 choosePhotoBtn 连接到名为 Choose Photo 的UIButton上
  2. 将 imageView 连接到 UIImageView
  3. 将各按钮的Touch Up Inside 回调连接到 getPhoto方法

当你按下 File’s Owner 时,Connection Inspector (连接检查器)应该像这样:

 

screenshot_01

 

关闭 Interface Builder

5. 实现 getPhoto 方法

打开 PhotoAppViewController.m a并nd add the following code:

@synthesize imageView,choosePhotoBtn, takePhotoBtn;
 
-(IBAction) getPhoto:(id) sender {
	UIImagePickerController * picker = [[UIImagePickerController alloc] init];
	picker.delegate = self;
 
	if((UIButton *) sender == choosePhotoBtn) {
		picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
	} else {
		picker.sourceType = UIImagePickerControllerSourceTypeCamera;
	}
 
	[self presentModalViewController:picker animated:YES];
}

首先创建一个新的UIImagePickerController对象。它是一个视图控制器,可以按任意视图控制器方式正常显示出来(显示于导航视图,加载于表格视图,呈现为模型视图控制器等)。然后,设置代理为我们的视图控制器。它表示当用户选取照片时,拾取器将调用类中的某个方法。

接着,确定哪个按钮被按下。由于两个按钮都连接到此方法上,我们需要使用 == 来确定到底哪个被按下。到底是显示照相机图片还是显示照片库图片是由拾取器的一个属性决定的。看看代码你就会很清楚。

最后,调用presentModalViewController。它将使拾取器以动画的形式从屏幕底向上移动,切换到视图。根据按下的按钮的不同,你将看到下面图像:

photo 3photo

 

6. 显示选择的图像

一旦选择了照片, ImagePicker 将回调 didFinishPickingMediaWithInfo。PhotoAppViewController.m 文件中进入下列代码:

- (void)imagePickerController:(UIImagePickerController *)picker
    didFinishPickingMediaWithInfo:(NSDictionary *)info {
	[picker dismissModalViewControllerAnimated:YES];
	imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
}
  

第一行代码隐藏拾取器。随后将图像视图的image 属性设置为返回的图像。拾取器返回一个NSDictionary对象。这是由于 UIImagePickerControllerMediaType 将指示返回的是视频还是图像。

iPhone Tutorial – PhotoApp.zip

原文见:Getting Images From The iPhone Photo Library Or Camera Using UIImagePickerController

http://www.icodeblog.com/2009/07/28/getting-images-from-the-iphone-photo-library-or-camera-using-uiimagepickercontroller/