LoginSignup
3
4

More than 5 years have passed since last update.

CoreGraphicsでRetina対応した画像を生成する

Last updated at Posted at 2015-04-11

概要

CoreGraphicsで画像を作るにあたり、Retinaディスプレイに対応したものを出力させます。

基本的には、

スクリーンのスケール*1を元に、
スケール倍の縮尺で画像を生成、UIImage格納時にスケールを指定する。

*1 Retinaなら2.0

と考えてください。

UIGraphicsBeginImageContextの場合

概要のとおり、
サイズ定義でスケール倍し、UIImage格納時にスケールを指定しています。

// メインスクリーンのスケールを取得
float scale = [[UIScreen mainScreen] scale];
// 生成画像のサイズ定義(スケール倍する)
const CGSize ICON_SIZE = CGSizeMake(24 * scale, 24 * scale);
const CGRect ICON_RECT = CGRectMake(0, 0, 24 * scale, 24 * scale);

/* 中略 */

// コンテキストよりイメージ取得
CGImageRef imageRef = CGBitmapContextCreateImage(context);
// UIImageの取得(スケールを指定)
UIImage *image = [UIImage imageWithCGImage:imageRef
                                     scale:scale
                               orientation:UIImageOrientationUp];

CGBitmapContextCreateの場合

コンテキスト開始を、UIGraphicsBeginImageContextではなくUIGraphicsBeginImageContextWithOptionsを用い、第3引数にスケールをセットします。

この一行だけで、自動的にスケール倍したイメージが生成され、UIImageへの格納もスケール指定は不要です。
また、第3引数が0なら、自動的にメインスクリーンのスケールが参照されます。

// 生成画像のサイズ定義(スケール倍は不要)
const CGSize ICON_SIZE = CGSizeMake(24, 24);

// コンテキストの開始(第3引数に0)
UIGraphicsBeginImageContextWithOptions(ICON_SIZE, NO, 0);

/* 中略 */

// 生成されたイメージの取得(スケール指定は不要)
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4