2011-12-13 63 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)];