Skip to content

Instantly share code, notes, and snippets.

@hisasann hisasann/ImageUtil.m
Created Jul 30, 2012

Embed
What would you like to do?
Objective-Cで画像のリサイズ系
#import "ImageUtil.h"
@implementation ImageUtil
// 幅を元に、リサイズ画像の幅・高さを算出する
+ (CGSize)resizeFromWidth:(CGFloat)width imageSize:(CGSize)imageSize {
CGFloat s_x = imageSize.width / width;
CGFloat s_y = imageSize.height / (imageSize.height / s_x);
CGFloat scale = MAX(s_x, s_y);
if (scale > 1) {
CGFloat new_x = imageSize.width / scale;
CGFloat new_y = imageSize.height / scale;
return CGSizeMake(new_x, new_y);
}
return imageSize;
}
// 幅を元に、UIImageのリサイズした場合のサイズを返す
+ (CGSize)resizeFromWidth:(CGFloat)width image:(UIImage *)image {
return [self resizeFromWidth:width imageSize:CGSizeMake(image.size.width, image.size.height)];
}
// 幅を元に、UIImageをリサイズし、UIImageを返す
+ (UIImage *)resizeImageFromWidth:(CGFloat)width image:(UIImage *)image {
CGSize resizedSize = [self resizeFromWidth:width image:image];
UIGraphicsBeginImageContext(resizedSize);
[image drawInRect:CGRectMake(0, 0, resizedSize.width, resizedSize.height)];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resizedImage;
}
// 幅・高さを元に、リサイズ画像の幅・高さを算出する
+ (CGSize)resizeFromSize:(CGSize)size imageSize:(CGSize)imageSize {
CGFloat widthRatio = imageSize.width / size.width;
CGFloat heightRatio = imageSize.height / size.height;
CGFloat ratio = (widthRatio < heightRatio) ? widthRatio : heightRatio;
CGSize resizedSize = CGSizeMake(size.width * ratio, size.height * ratio);
return resizedSize;
}
// 幅・高さを元に、UIImageをリサイズして、CGSizeを返す
+ (CGSize)resizeFromSize:(CGSize)size image:(UIImage *)image {
CGFloat widthRatio = size.width / image.size.width;
CGFloat heightRatio = size.height / image.size.height;
CGFloat ratio = (widthRatio < heightRatio) ? widthRatio : heightRatio;
CGSize resizedSize = CGSizeMake(image.size.width * ratio, image.size.height * ratio);
return resizedSize;
}
// 幅・高さを元に、UIImageをリサイズして、UIImageを返す
+ (UIImage *)resizeImageFromSize:(CGSize)size image:(UIImage *)image {
CGSize resizedSize = [self resizeFromSize:(CGSize) size image:image];
UIGraphicsBeginImageContext(resizedSize);
[image drawInRect:CGRectMake(0, 0, resizedSize.width, resizedSize.height)];
UIImage *resizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resizedImage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.