如何在iOS中裁剪到信箱

时间:2012-06-01 05:30:52

标签: ios image

在IOS中如何将矩形图像裁剪为方形信箱,使其保持原始宽高比,其余空格用黑色填充。例如。 transloadit用于裁剪/调整图像大小的“pad”策略。

http://transloadit.com/docs/image-resize

3 个答案:

答案 0 :(得分:2)

对于那些偶然发现这个问题并且更多人喜欢它而没有明确答案的人,我写了一个简洁的小类,通过直接修改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;
}

答案 1 :(得分:0)

您必须使用contentMode设置UIImageView的UIViewContentModeScaleAspectFit。如果您使用故事板,也可以为UIImageView找到此选项。

将UIImageView的backgroundColor设置为黑色(或您选择的其他颜色)。

答案 2 :(得分:0)

为了方便起见 - 继续快速改写@Dima的答案:

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