2010-02-02 106 views
0
UIImage *image = [[UIImage alloc] initWithContentsOfFile:@"popup.png"]; 
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 

    [self.view addSubview:imageView]; 

    [image release]; 
    [imageView release]; 

該代碼位於UIViewcontroller對象內。它編譯得很好,但運行時,子視圖看起來不會被添加。爲什麼我的UIImageView不會顯示爲子視圖?

我累了。

回答

1

initWithContentsOfFile需要完整的文件路徑,而不僅僅是文件名。

更換,你初始化的UIImage有以下線路:

NSBundle *bundle = [NSBundle mainBundle]; 
UIImage *image = [[UIImage alloc] initWithContentsOfFile: [bundle pathForResource:@"popup" ofType:@"png"]]; 

更簡單的方法將是使用的UIImage類

UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"popup.png"]]; 

imageNamed:方法,你不要擔心路徑到文件的詳細信息。只需要initWithImage:方法緩存圖像。根據您的應用程序可能是好的或壞主意。

希望這會有所幫助!

0

嘗試使用:

UIImage *image = [UIImage imageNamed:@"popup.png"]; 

,並關閉過程,擺脫了[image release];,因爲在該解決方案中image會被自動釋放。

注意,此解決方案將不會是好的,如果你有這個名字不止一個圖像(在不同的文件夾/組)...

0

您的ImageView需要一個框架。 imageView.frame = CGRectMake(0,0,320,480);

0

我知道這個問題現在已經老了,但有些用戶仍然可以從答案中獲益。

像其他人一樣,嘗試使用[UIImage imagedNamed:]而不是initWithContentsOfFile

而它沒有顯示在屏幕上的原因是你沒有設置圖像的位置。您可以通過設置圖像視圖的框架或將其中心設置在單個點來解決此問題。爲了將圖像視圖在屏幕的中心:

UIImage *image = [UIImage imageNamed:@"image.png"]; 
UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; 

imageView.center = [self.view center]; 

// or if you want to set a frame instead 
// CGRect imageFrame = CGRectMake(x,y,width,height); 
// [imageView setFrame:imageFrame]; 

[self.view addSubView:imageView]; 

享受:)

相關問題