2012-06-01 4 views

답변

1

이 질문에 넘어 지거나 더 명확한 대답이없는 사람이라면 누구나보기를 수정하는 대신 UIImage을 직접 수정하여 모델 수준에서이를 수행 할 수 있습니다. 이 메소드를 사용하기 만하면 어느 쪽이 길어도 반환 된 이미지가 사각형 모양으로 레터 박스로 표시됩니다. 그냥 편의를 위해

- (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

당신은 UIViewContentModeScaleAspectFit로있는 UIImageView의 contentMode을 설정해야합니다. 스토리 보드를 사용하는 경우 UIImageView에 대한이 옵션을 찾을 수도 있습니다.

UIImageView의 backgroundColor을 검은 색 (또는 원하는 다른 색)으로 설정하십시오.

0

- @ 디마의 답변을 heres 신속한 재 작성 :

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 
    } 
}