hachinoBlog

hachinobuのエンジニアライフ

UIImageのリサイズ

背景

画像の大きさをコードでリサイズしたかったのでUIImageのリサイズ方法を調べた。

やり方

//UIImageのリサイズメソッド
- (UIImage *)resizeImage:(UIImage *)image rect:(CGRect)rect
{
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0);
    [image drawInRect:rect];
    UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetInterpolationQuality(context, kCGInterpolationHigh);
    UIGraphicsEndImageContext();
    return resizedImage;
}

//使う側
UIImage *image = [UIImage imageNamed:@"imageName"]; //100x100の画像とする
CGRect imageRect = (CGRect){ CGPointZero, CGSizeMake(50.0f, 50.0f) }; //50x50にリサイズ
image = [self resizeImage:image rect:imageRect];

UIGraphicsBeginImageContextWithOptions(サイズ, 透過有無(NOで透過有), スケール指定(0でデバイス固有));

※0でデバイス固有というのはRetinaディスプレイであれば100x100は200x200の解像度になるよ。という意味です。