2012-06-01 78 views

回答

1

對於任何人在這個問題上磕磕絆絆,還有​​許多人沒有明確的答案,我寫了一個整潔的小類,通過直接修改UIImage來完成這一點,而不僅僅是修改視圖。只需使用這種方法,返回的圖像將以letterbox方式呈現方形,而不管哪一邊更長。

- (UIImage *) letterboxedImageIfNecessary 
{ 
    CGFloat width = self.size.width; 
    CGFloat height = self.size.height; 

    // no letterboxing needed, already a square 
    if(width == height) 
    { 
     return self; 
    } 

    // find the larger side 
    CGFloat squareSize = MAX(width,height); 

    UIGraphicsBeginImageContext(CGSizeMake(squareSize, squareSize)); 

    // draw black background 
    CGContextRef context = UIGraphicsGetCurrentContext(); 
    CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 1.0); 
    CGContextFillRect(context, CGRectMake(0, 0, squareSize, squareSize)); 

    // draw image in the middle 
    [self drawInRect:CGRectMake((squareSize - width)/2, (squareSize - height)/2, width, height)]; 

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return newImage; 
} 
0

你要設置的UIImageView的contentModeUIViewContentModeScaleAspectFit。如果您使用故事板,您也可以爲UIImageView找到此選項。

將UIImageView的backgroundColor設置爲黑色(或您選擇的其他顏色)。

0
只是爲了方便

- 繼承人@迪馬的回答迅速改寫:

import UIKit 

extension UIImage 
{ 
    func letterboxImage() -> UIImage 
    { 
     let width = self.size.width 
     let height = self.size.height 

     // no letterboxing needed, already a square 
     if(width == height) 
     { 
      return self 
     } 

     // find the larger side 
     let squareSize = max(width, height) 

     UIGraphicsBeginImageContext(CGSizeMake(squareSize, squareSize)) 

     // draw black background 
     let context = UIGraphicsGetCurrentContext() 
     CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 1.0) 
     CGContextFillRect(context, CGRectMake(0, 0, squareSize, squareSize)) 

     // draw image in the middle 
     self.drawInRect(CGRectMake((squareSize-width)/2, (squareSize - height)/2, width, height)) 

     let newImage = UIGraphicsGetImageFromCurrentImageContext() 
     UIGraphicsEndImageContext() 
     return newImage 
    } 
}