如何在UIImageView中显示UIImage?

时间:2013-09-10 21:36:35

标签: ios objective-c uiimageview uiimage storyboard

我正在玩Xcode 5和故事板。我正处于使用相机捕获UIImage的位置,但是在我捕获后我无法弄清楚如何在手机上显示图像。我已经指定了IBOutlet UIImageView并将其值设置为我从相机捕获的图像,但这似乎根本没有做任何事情。

这是我的界面:

@interface HCViewController ()

@property (nonatomic, retain) IBOutlet UIImageView *image;

@end

这是我的didFinishPickingWithMediaInfo方法:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // Get the picture from the camera
    UIImage *imageFromCamera = [info objectForKey:UIImagePickerControllerEditedImage];

    // Set the IBOutlet UIImageView to the picture from the camera
    // This does nothing as far as I can tell
    self.image = [[UIImageView alloc] initWithImage:imageFromCamera];

    // Let's take a closer look at this
    NSLog(@"%@", self.image);

    // Close the camera view controller
    [self dismissViewControllerAnimated:YES completion:nil];
}

这是我在self.image的记录器中看到的:

2013-09-10 17:17:45.169 YourMom[6136:60b] <UIImageView: 0x1556fdc0; frame = (0 0; 0 0); userInteractionEnabled = NO; layer = <CALayer: 0x155d5b10>>

我的故事板有一个视图控制器,有两个不同的场景,可以来回滑动。两个场景都具有“视图”,其中“图像视图”作为子项。每个图像视图都有“引用插座”,它们似乎连接到我在界面中定义的image变量。但是,只需设置image的值不会更改手机显示。

在阅读了这个问题后:How can I change the image displayed in an UIImageView programmatically?我尝试了[self.image setImage:image],但这似乎也没有做任何事情。如何告诉Xcode我希望image显示在视图中?

4 个答案:

答案 0 :(得分:3)

你的错误在于:

self.image = [[UIImageView alloc] initWithImage:imageFromCamera];

因为您正在使用Storyboard,所以UIImageView将为您初始化。通过执行这行代码,您将丢弃旧的UIImageView并将其替换为没有框架的新UIImageView

你只需要这样做:

[self.image setImage:imageFromCamera]

此外,您可能从信息中获取了错误的图像。请尝试UIImagePickerControllerOriginalImage而不是UIImagePickerControllerEditedImage。 希望这有用,欢呼!

答案 1 :(得分:1)

// this is your delegate method to set the image taken from your camera

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

 // Get the picture from the camera
    UIImage *imageFromCamera = [info objectForKey:UIImagePickerControllerEditedImage];

 // alloc image view as you have to set it image on it
    UIImageView *imgView = [[UIImageView alloc]init];
    imgView.image = imageFromCamera;

// you can also set the image on button like this 
    UIImage *imageFromCamera = [info objectForKey:UIImagePickerControllerEditedImage];
// imgBtn is UIButton property
    [self.imgBtn setImage:imageFromCamera forState:UIControlStateNormal];

// Let's take a closer look at this
    NSLog(@"%@", self.image);

// Close the camera view controller
    [self dismissViewControllerAnimated:YES completion:nil];

}

答案 2 :(得分:1)

UIImage View有一个名为image的属性。

此属性的类型为UIImage

因此,如果您有UIImage,则可以按如下方式设置属性:

imageView.image = image;

答案 3 :(得分:0)

您可以尝试使用此代码来显示图片。

imageView.image : UIImage = UIImage(named: "YourImageName")

希望这可以帮助您解决问题。