iOS:UIImageView示例代码

时间:2012-01-28 00:32:40

标签: iphone ios xcode uiimageview

我正在编写一个应用程序,允许用户从相机胶卷上传照片并将其保存在应用程序中。唯一的问题是我不知道从哪里开始。我在UIImageView上阅读了Apples文档,但这似乎没有像通常那样有用。我想知道是否有人可以指出我在一些示例代码的正确方向上通常做同样的事情?

谢谢!

1 个答案:

答案 0 :(得分:2)

让我们先清楚一点

  • UIImageView是一个用于显示UIImage的可视组件(无论它们来自何处)
  • UIImagePickerController是Apple提供的用于获取图片的组件(来自用户相册或直接来自相机)
  • 保存图像意味着将其存储在本地文件系统

现在让我们看看它实际上是如何结合在一起的:

首先,您需要创建一个UIImagePickerController,定义图像的来源并设置一个委托来处理返回的图像。这些方面的东西:

// Always make sure to test if the source you want is available
if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
{
    UIImagePickerController *imagePicker =  [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    imagePicker.mediaTypes = [NSArray arrayWithObjects:
                              (NSString *) kUTTypeImage,
                              nil];
    imagePicker.allowsEditing = NO;

//Our image picker is ready - now let's show it to the user
    [self presentModalViewController:imagePicker  animated:YES];
    [imagePicker release];

}

这会将图像选择器调出给用户(特别是相机 - 您可以使用媒体类型和来源 - 查找UIImagePickerController Reference以查看您还有其他选项。

现在 - 您必须实际处理从用户处获得的图像,并通过委托方法实现完成:

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
//All the info from the image - including the image itself - are stored in the info dictionary.

NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];

if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];

//Now - we have a reference to the image as a UIImage, so we can display it in a UIImageView or save it to disk or upload to a webserver. To show it - just set your imageView's image to the image
    imageView.image = image;
}
}