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 に答える