2011-12-13 22 views
2

出于某种原因,我只能在每次迭代使用不同图像分配/初始化它时显示UIImageView。奇怪的是我知道正在加载图像数据,因为我正在对图像执行处理,并且处理按预期工作。总之,这里有两种方法我尝试:UIImageView仅在我调用initWithImage时显示

// interface 
@interface ViewController : UIViewController <UIAlertViewDelegate> 
{ 

    UIImageView *imageView; 

} 

@property (nonatomic, retain) UIImageView *imageView; 

@end 

// implementation 
@implementation ViewController 

@synthesize imageView; 

//... 

- (void) loadAndDisplayImage { 

    // Load testing image 
    UIImage *testImg; 
    testImg = [UIImage imageNamed:@"Test.png"]; 

    self.imageView = [[UIImageView alloc] initWithImage:testImg]; 

    //size of imageView rect 
    CGRect frame = self.imageView.frame; 
    int ivw = frame.size.width; 
    int ivh = frame.size.height; 

    //... 

} 

@end 

当我用这个方法self.imageView = [[UIImageView alloc] initWithImage:testImg];ivwivh具有有效的值并显示图像。但是,如果我改变实现这样:

// implementation 
@implementation ViewController 

@synthesize imageView; 

//... 

- (void) viewDidLoad { 

    self.imageView = [[UIImageView alloc] init]; 
    [self loadAndDisplayImage]; 

} 

- (void) loadAndDisplayImage { 

    // Load testing image 
    UIImage *testImg; 
    testImg = [UIImage imageNamed:@"Test.png"]; 

    self.imageView.image = testImg; 

    //size of imageView rect 
    CGRect frame = self.imageView.frame; 
    int ivw = frame.size.width; 
    int ivh = frame.size.height; 

    //... 

} 

@end 

我在哪里设置使用self.imageView.image = testImg;形象,价值ivwivh均为零,并且不显示图像,但图像的后续处理仍然是准确的。在这两种情况下,我都会使用[self doRecognizeImage:self.imageView.image];将图像发送到处理。我无法弄清楚这是如何可能的。如果图像无法显示时处理失败,这对我来说会更有意义。

想法?谢谢。

回答

7

的问题是,当你设置image属性上已经init'd UIImageView,帧大小不更新以匹配新的图像尺寸(不像initWithImage:)。

只要你有这样的问题,它总是值得万一检查出docs你错过了一些东西:

设置图像属性不会改变一个UIImageView的大小。 调用sizeToFit来调整视图的大小以匹配图像。

所以,添加一个调用sizeToFit你设置了像特性:

self.imageView.image = testImg; 
[self.imageView sizeToFit]; 

作为一个方面说明,我只用self.点符号,当你写的财产,不读书,或者调用方法。换句话说,你只需写作即可脱身:

// we are not setting imageView itself here, only a property on it 
imageView.image = testImg; 

// this is a method call, so "self." not needed 
[imageView sizeToFit];  
+0

感谢您的建议! – 2011-12-14 16:06:32

2

您的图像视图可能无法调整图像大小,因此您需要将图像加载到零大小的帧中。尝试手动将图像视图的框架设置为其他值。沿着线的东西:

UIImageView* test = [[UIImageView alloc] init]; 
[test setFrame:CGRectMake(0, 0, 100, 100)];