IOS에서 어떻게 사각형의 이미지를 사각형의 레터 박스로 자르면 원래의 종횡비가 유지되고 나머지 공간은 검은 색으로 채워지 는가? 예 : transloadit이 이미지를 자르고 크기를 조정하는 데 사용하는 "패드"전략.iOS에서 레터 박스로 자르는 방법
http://transloadit.com/docs/image-resize
IOS에서 어떻게 사각형의 이미지를 사각형의 레터 박스로 자르면 원래의 종횡비가 유지되고 나머지 공간은 검은 색으로 채워지 는가? 예 : transloadit이 이미지를 자르고 크기를 조정하는 데 사용하는 "패드"전략.iOS에서 레터 박스로 자르는 방법
http://transloadit.com/docs/image-resize
이 질문에 넘어 지거나 더 명확한 대답이없는 사람이라면 누구나보기를 수정하는 대신 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;
}
당신은 UIViewContentModeScaleAspectFit
로있는 UIImageView의 contentMode
을 설정해야합니다. 스토리 보드를 사용하는 경우 UIImageView에 대한이 옵션을 찾을 수도 있습니다.
UIImageView의 backgroundColor
을 검은 색 (또는 원하는 다른 색)으로 설정하십시오.
- @ 디마의 답변을 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
}
}