2010-06-23 28 views
0

我希望用戶能夠從他們的照片中選擇圖片並將其設置爲主視圖的背景。如何設置圖像作爲UIView的背景,但正確縮放?

這是目前我在做什麼:

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info { 
    [picker dismissModalViewControllerAnimated:YES]; 

    UIImage *testimg = [info objectForKey:UIImagePickerControllerOriginalImage]; 

    NSArray * sysPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 

    filePath = [[NSString alloc] initWithFormat: @"%@/%@", [sysPaths objectAtIndex: 0], @"testimg.png"]; 
    if ([UIImagePNGRepresentation (testimg) writeToFile:filePath atomically:YES]) ; 

    self.backgroundColor= [[UIColor alloc] initWithPatternImage:[[UIImage alloc] initWithContentsOfFile: filePath]]; 


    } 
此方法

除了能在速度上有點遲緩,這個偉大的工程!但有一個問題。當選擇圖像時,圖像不能正確縮放。我將如何解決這個問題?

由於提前,

-David

+0

此外,你已經有了圖像。設備上的文件I/O非常慢,因此只需使用已獲取的圖像,而不是讀取剛寫入的圖像。您也可以考慮將它寫在另一個線程上,以便該方法可以立即返回。你這樣做的方式,你必須等待圖像被壓縮,寫入,然後再次讀取,然後再解壓縮,所以自然會感覺有點呆滯:) – 2010-06-23 02:45:51

回答

1

尤其具有contentMode屬性一看的UIImageView。

imageView.contentMode = UIViewContentModeScaleAspectFit;

+0

問題是我使用UIImage,而不是UIImageView和它看起來像UIImage有一個名爲contentMode的屬性... – bobbypage 2010-06-23 02:34:12

+0

您必須在視圖中顯示UIImage,但找到該視圖並查找該屬性。 – Gary 2010-06-23 02:37:43

+0

所以我試着通過代碼來改變內容模式,甚至我也沒有看到區別。無論我選擇哪種內容模式,我都會繼續看到同樣的問題。我一直在使用self.contentMode = UIViewContentModeScaleAspectFit; – bobbypage 2010-06-23 02:43:15