2009-11-09 92 views
33

我使用這個代碼在iPhone上調整圖像大小:調整UIImage的縱橫比?

CGRect screenRect = CGRectMake(0, 0, 320.0, 480.0); 
UIGraphicsBeginImageContext(screenRect.size); 
[value drawInRect:screenRect blendMode:kCGBlendModePlusDarker alpha:1]; 
UIImage *tmpValue = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 

這是偉大的工作,只要圖像的長寬比匹配,新調整後的圖像中。我想修改它以保持正確的高寬比,並在圖像不顯示的任何位置放置黑色背景。所以我仍然會得到一個320x480的圖像,但在頂部和底部或兩側都有黑色,這取決於原始圖像的大小。

有沒有一種簡單的方法來做到這一點,類似於我在做什麼?謝謝!

+0

下面是保持縱橫比的文章: http://stackoverflow.com/questions/7645454/resize-uiimage-by-keeping-aspect-ratio-and-width – 2013-05-12 02:05:45

回答

52

您設置的屏幕矩形,這樣做以下後決定什麼RECT繪製圖像:

float hfactor = value.bounds.size.width/screenRect.size.width; 
float vfactor = value.bounds.size.height/screenRect.size.height; 

float factor = fmax(hfactor, vfactor); 

// Divide the size by the greater of the vertical or horizontal shrinkage factor 
float newWidth = value.bounds.size.width/factor; 
float newHeight = value.bounds.size.height/factor; 

// Then figure out if you need to offset it to center vertically or horizontally 
float leftOffset = (screenRect.size.width - newWidth)/2; 
float topOffset = (screenRect.size.height - newHeight)/2; 

CGRect newRect = CGRectMake(leftOffset, topOffset, newWidth, newHeight); 

如果你不想放大比screenRect較小的圖像,確保factor大於或等於1(例如factor = fmax(factor, 1))。

要獲取黑色背景,您可能只想將上下文顏色設置爲黑色,並在繪製圖像之前調用fillRect。

+0

'value'是可變Cory正在使用來存儲源圖像。 – 2011-03-17 00:07:14

+0

@弗蘭克施密特,我可以檢查我可以如何設置上下文爲黑色的情況下? – Zhen 2011-07-13 14:00:38

+0

雖然我記得包含math.h(我使用的是XCode 4.0),但我得到了「編譯器拋出的函數'隱式聲明'max'',因爲改變了:'float factor = max(...'to'float factor = MAX(...'all caps)解決了這個問題FWIW我需要重新調整UIImage(而不是UIImageView)的原因是因爲我將圖像設置爲默認樣式的UITableCell,這有助於避免需要實現自定義UITableCell。 _感謝Frank提供了一個很棒的解決方案!_ – cleverbit 2012-02-22 12:01:39