2013-11-26 148 views
4

我正在研究一個具有數百個背景圖像的通用應用程序。爲了節省磁盤空間並防止進一步的重複和磁盤垃圾郵件,我想重新使用非retina @ 1x iPad圖像作爲retina @ 2x iPhone圖像。如何在iPhone上將@ 1x iPad圖像加載爲@ 2x圖像?

實施例:

[email protected] 
background125_iPad.png 

iPhone 4和5具有不同的縱橫比,所以我將縮放1024×768圖像,以適應。

但問題是,如果我用這對iPhone 5:

UIImage *img = [UIImage imageNamed:@"background125_iPad.png"]; 

那麼,iOS將盡量比我聰明,並挑選了巨大的內存怪獸@「[email protected]」版本。

有沒有辦法說:「iOS,看,我比你聰明,我希望你加載這個文件,我真的是這個文件,這個文件,把它當作@ 2x版本的比例因子爲2。「這樣它真的會加載請求的「background125_iPad.png」文件,但是那麼UIImageView的行爲就好像它有512 x 384點(= 1024x768像素)?

我假設UIImage imageNamed是不是要走的路?

回答

2

我不認爲你可以關閉該功能。

但是你可以這樣做:

UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"background125_iPad" ofType:@"png"]]; 
UIImage *scaledImage = [UIImage imageWithCGImage:[img CGImage] 
          scale:[[UIScreen mainScreen] scale] 
          orientation:img.imageOrientation]; 

這不會自動添加設備特定後綴。 我會建議封裝到這UIImage的類別,簡單使用:)

+0

是的,這似乎加載正確的圖像,但比例因子是錯誤的。 iOS應將其視爲@ 2x圖像。你會怎麼做? – openfrog

+0

你試過把它縮放到[UIScreen mainScreen] .scale嗎? –

+0

如果我沒有弄錯,規模是隻讀的。但也許我找到了解決方案。看到我的回答(相信你:-)) – openfrog

1

要加載圖像嚴格按照規定和得到的比例因子權,這應該工作:

UIImage *img = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"background125_iPad" ofType:@"png"]]; 
img = [UIImage imageWithCGImage:[tmpImage CGImage] 
              scale:[[UIScreen mainScreen] scale] 
            orientation:UIImageOrientationUp]; 

感謝格熱戈日爲-imageWithContentsOfFile:[[UIScreen mainScreen] scale]提示。

+0

但是,比你有其他設備的問題:)更好的使用[UIScreen mainScreen] .scale –

+0

更新!那是對的嗎? – openfrog

+0

我更新了我的答案 - 您可以從img取得的方向以及哪個更好imho –

相關問題