私のiPhoneアプリでは、カメラで写真を撮り、それを290*390ピクセルにリサイズしたいと考えています。私はこの方法で画像をリサイズしていました。
UIImage *newImage = [image _imageScaledToSize:CGSizeMake(290, 390)
interpolationQuality:1];
完璧に動作していましたが、これは文書化されていない関数なので、iPhone OS4ではもう使えません。
では、UIImageのサイズを変更する一番簡単な方法は何でしょうか?
最も簡単な方法は、UIImageView
のフレームを設定して、contentMode
にリサイズオプションの一つを設定することです。
また、実際に画像をリサイズする必要がある場合には、このユーティリティメソッドを使用することもできます。
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
//UIGraphicsBeginImageContext(newSize);
// In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
// Pass 1.0 to force exact pixel size.
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
使用例です。
#import "MYUtil.h"
…
UIImage *myIcon = [MYUtil imageWithImage:myUIImageInstance scaledToSize:CGSizeMake(20, 20)];
Trevor Howardは、リサイズをうまく処理するUIImage categoriesを公開しています。何はともあれ、このコードを例として使うことができます。
注:iOS 5.1の時点で、この回答は無効かもしれません。以下のコメントを参照してください。
また、このような方法も見たことがあります(ボタンはサイズ変更ができないので、UIButtons
のNormalとSelectedの状態で使用しています)。 クレジットはオリジナルの作者の方にお願いします。
まず、UIImageResizing.h
とUIImageResizing.m
という空の.hと.mのファイルを作ります。
// Put this in UIImageResizing.h
@interface UIImage (Resize)
- (UIImage*)scaleToSize:(CGSize)size;
@end
// Put this in UIImageResizing.m
@implementation UIImage (Resize)
- (UIImage*)scaleToSize:(CGSize)size {
UIGraphicsBeginImageContext(size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(context, 0.0, size.height);
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(0.0f, 0.0f, size.width, size.height), self.CGImage);
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
@end
その.hファイルを、この関数を使用する予定の.mファイルにインクルードして、次のように呼び出します。
UIImage* image = [UIImage imageNamed:@"largeImage.png"];
UIImage* smallImage = [image scaleToSize:CGSizeMake(100.0f,100.0f)];