我在xcode中用Cocoa编写了一个iPhone应用程序.我找不到任何教程或示例代码,说明如何使用内置摄像头拍照.我该怎么做呢?我在哪里可以找到好消息?
谢谢!
只需将以下代码复制并粘贴到项目中即可获得完全实现的功能.
其中takePhoto 和chooseFromLibrary 是我自己的方法名称,将在按钮触摸时调用.
确保将适当按钮的出口引用到这些方法中.
-(IBAction)takePhoto :(id)sender { UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init]; if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { [imagePickerController setSourceType:UIImagePickerControllerSourceTypeCamera]; } // image picker needs a delegate, [imagePickerController setDelegate:self]; // Place image picker on the screen [self presentModalViewController:imagePickerController animated:YES]; } -(IBAction)chooseFromLibrary:(id)sender { UIImagePickerController *imagePickerController= [[UIImagePickerController alloc] init]; [imagePickerController setSourceType:UIImagePickerControllerSourceTypePhotoLibrary]; // image picker needs a delegate so we can respond to its messages [imagePickerController setDelegate:self]; // Place image picker on the screen [self presentModalViewController:imagePickerController animated:YES]; } //delegate methode will be called after picking photo either from camera or library - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { [self dismissModalViewControllerAnimated:YES]; UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage]; [myImageView setImage:image]; // "myImageView" name of any UIImageView. }
使用UIImagePickerController
.这里有一个很好的教程.
http://www.zimbio.com/iPhone/articles/1109/Picking+Images+iPhone+SDK+UIImagePickerController
您应该将源类型设置为UIImagePickerControllerSourceTypeCamera
或UIImagePickerControllerSourceTypePhotoLibrary
.请注意,这两种类型会在屏幕上显示非常不同的显示.你应该仔细测试.特别是,如果你正在嵌套UIImagePickerController
内部a UINavigationController
,如果你不小心,最终可能会有多个导航栏和其他奇怪的效果.
另见此主题