0

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

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

4

3 回答 3

2

对于在没有明确答案的情况下偶然发现这个问题以及更多类似问题的人,我编写了一个简洁的小类别,它通过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;
}
于 2014-05-23T05:52:07.510 回答
1

只是为了方便 - 这里是@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
    }
}
于 2015-09-22T06:50:41.387 回答
0

您必须设置contentModeUIImageView 与UIViewContentModeScaleAspectFit. 如果您使用故事板,您还可以为 UIImageView 找到此选项。

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

于 2012-06-01T05:39:12.730 回答