UIViewを画像にレンダリングするための実装(Retinaディスプレイでも機能します)。
helper.hファイル:
@interface UIView (Ext)
- (UIImage*) renderToImage;
@end
helper.mファイルの所属する実装:
#import <QuartzCore/QuartzCore.h>
@implementation UIView (Ext)
- (UIImage*) renderToImage
{
// IMPORTANT: using weak link on UIKit
if(UIGraphicsBeginImageContextWithOptions != NULL)
{
UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0);
} else {
UIGraphicsBeginImageContext(self.frame.size);
}
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
0.0はスケールファクターです。ビットマップに適用する倍率。0.0の値を指定すると、倍率はデバイスのメイン画面の倍率に設定されます。
レイヤーオブジェクトで関数を呼び出しているため、 QuartzCore.frameworkもプロジェクトに配置する必要があります。
UIKitフレームワークでウィークリンクを有効にするには、左側のナビゲーターでプロジェクトアイテムをクリックし、プロジェクトターゲット->ビルドフェーズ->リンクバイナリをクリックして、UIKitフレームワークで「オプション」(ウィーク)タイプを選択します。
これは、UIColor、UIImage、NSArray、NSDictionary、...の同様の拡張機能を備えたライブラリです。