縮小処理
こんな感じ。
@implementation UIImage (extension)
- (UIImage*)imageByShrinkingWithSize:(CGSize)size
{
CGFloat widthRatio = size.width / self.size.width;
CGFloat heightRatio = size.height / self.size.height;
CGFloat ratio = (widthRatio < heightRatio) ? widthRatio : heightRatio;
if (ratio >= 1.0) {
return self;
}
CGRect rect = CGRectMake(0, 0,
self.size.width * ratio,
self.size.height * ratio);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
[self drawInRect:rect];
UIImage* shrinkedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return shrinkedImage;
}
UIImage のカテゴリとして実装した。縦横比は保持したまま、与えられたサイズ内に収まる最大の画像を返す。参考情報
- 補間方法を指定してUIImageを縮小する(1) - tosh-tの日記
- 画像を縮小する時の補完方法について



tokyopengwyn
2011年5月10日 21:24
あのー...
UIGraphicsBeginImageContext(rect.size);
は
UIGraphicsBeginImageContext(size);
ではないですか?
縦横比が保持されないのでびっくりしました。
それと、
CGContextRef context = UIGraphicsGetCurrentContext();
は、必要ない気がします。
tokyopengwyn
2011年5月10日 21:24
あのー...
UIGraphicsBeginImageContext(rect.size);
は
UIGraphicsBeginImageContext(size);
ではないですか?
縦横比が保持されないのでびっくりしました。
それと、
CGContextRef context = UIGraphicsGetCurrentContext();
は、必要ない気がします。
xcatsan says:
2011年5月10日 22:25
こんばんは。コメントどうも。
CGContextRef context = UIGraphicsGetCurrentContext();
は指摘の通り不要ですね。
UIGraphicsBeginImageContext(rect.size);
ですが、うまくいかないですか?私のところではうまくいってますよ。
UIGraphicsBeginImageContext(size);
にするとできあがった画像サイズは縦横比が保持されません。
(例えば、[image imageByShrinkingWithSize:CGSizeMake(100,900)] と
すると元の画像の縦横比とは無関係に 100x900サイズの画像が返されます)。
では。
xcatsan says:
2011年5月10日 22:25
こんばんは。コメントどうも。
CGContextRef context = UIGraphicsGetCurrentContext();
は指摘の通り不要ですね。
UIGraphicsBeginImageContext(rect.size);
ですが、うまくいかないですか?私のところではうまくいってますよ。
UIGraphicsBeginImageContext(size);
にするとできあがった画像サイズは縦横比が保持されません。
(例えば、[image imageByShrinkingWithSize:CGSizeMake(100,900)] と
すると元の画像の縦横比とは無関係に 100x900サイズの画像が返されます)。
では。