LoginSignup
5

More than 5 years have passed since last update.

画像を長い方を指定してリサイズする

Posted at

参考URL
http://shinen1.wordpress.com/2012/08/16/objective-c-uiimageのサイズ変更/

上記サイトを参考にさせていただきました。

縦横のアスペクト比を固定のまま,入力画像の幅,高さのうち長い方を指定されたサイズに縮小した画像を得るには次のようなメソッドを作成したら行けました。

/**
 * 画像リサイズ
 */
- (UIImage *)resizeImage:(UIImage *)sourceImage toSize:(CGFloat)newSize
{
    UIImage *destinationImage = [[UIImage alloc] init];
    CGFloat currentWidth = sourceImage.size.width;
    CGFloat currentHeight = sourceImage.size.height;
    CGFloat newWidth, newHeight;

    if (newSize == 0) {
        newWidth = newHeight = 0;

    } else if (currentHeight < currentWidth) {
        newHeight = floorf(currentHeight * newSize / currentWidth);
        newWidth = newSize;

    } else if (currentWidth <= currentHeight) {
        newWidth = floorf(currentWidth * newSize / currentHeight);
        newHeight = newSize;

    }

    UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
    [sourceImage drawInRect:CGRectMake(0, 0, newWidth, newHeight)];
    destinationImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return destinationImage;
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5