2011-03-02 99 views
0

我想以編程方式將圖像設置爲UIImageView,但它不起作用。我有以下代碼。IPhone UIImageView圖像

[image setImage:[UIImage imageNamed:[self localImagePath:NO]]]; 

-(NSString *)localImagePath:(BOOL)forSave { 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSPicturesDirectory, NSUserDomainMask, YES); 
    NSString *picturesDirectory = [paths objectAtIndex:0]; 
    NSString *picturesPath = [picturesDirectory stringByAppendingPathComponent:@"image.png"]; 
    if (forSave || [[NSFileManager defaultManager] fileExistsAtPath:picturesPath]) { 
     return picturesPath; 
    } 
    else { 
     return [[NSBundle mainBundle] pathForResource:@"image" ofType:@"png"]; 
    } 
} 

是否有可能像設置爲UIImageView的來自不同媒介的運行時間?

回答

4

imageNamed:方法只將文件名作爲參數,而不是路徑。它也只會在主包中查找該文件。改爲使用imageWithContentsOfFile:

+0

我試過你,它在半測試中工作。我仍然需要做全面的測試。你確定函數「imageWithContentsOfFile」將適用於圖片目錄中的圖片嗎? – Neutralizer 2011-03-02 15:55:22

1

你將不得不使用兩種不同的方式來加載圖像

[UIImage imageNamed: name]基於一個

[UIImage imageWithContentsOfFile: filename]的資源爲你本地找不到一個。

考慮更改您的方法以返回UIImage並在內部使用適當的加載方法。

+0

我第一次嘗試你的指導,它沒有工作。 – Neutralizer 2011-03-02 15:54:14

0

使用[UIImage imageWithContentsOfFile:[self localImagePath:NO]]而不是[UIImage imageNamed:...]作爲使用localImagePath方法找到的那個。

+0

是的,它的工作!乾杯! – Neutralizer 2011-03-02 15:56:16