甘いものが好きです

iOS App開発時に感じた疑問や課題、その他の雑感などを書いていきます。

文字列(NSStringオブジェクト)を画像化する方法

文字列を画像化する方法を調べてみたら、オフスクリーン描画をしてグラフィックスコンテキストから画像を得る方法が簡単だった。

上記のページを参考にして、指定されたサイズの領域の中央に文字列を描画して画像化するコードを書いてみた。

- (UIImage *)imageWithText:(NSString *)text fontSize:(CGFloat)fontSize rectSize:(CGSize)rectSize {

    // 描画する文字列のフォントを設定。
    UIFont *font = [UIFont systemFontOfSize:fontSize];

    // オフスクリーン描画のためのグラフィックスコンテキストを作る。
    if (UIGraphicsBeginImageContextWithOptions != NULL)
        UIGraphicsBeginImageContextWithOptions(rectSize, NO, 0.0f);
    else
        UIGraphicsBeginImageContext(rectSize);

    /* Shadowを付ける場合は追加でこの部分の処理を行う。
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetShadowWithColor(ctx, CGSizeMake(1.0f, 1.0f), 5.0f, [[UIColor grayColor] CGColor]);
    */

    // 文字列の描画領域のサイズをあらかじめ算出しておく。
    CGSize textAreaSize = [text sizeWithFont:font constrainedToSize:rectSize];

    // 描画対象領域の中央に文字列を描画する。
    [text drawInRect:CGRectMake((rectSize.width - textAreaSize.width) * 0.5f,
                                (rectSize.height - textAreaSize.height) * 0.5f,
                                textAreaSize.width,
                                textAreaSize.height) 
            withFont:font 
       lineBreakMode:NSLineBreakByWordWrapping 
           alignment:NSTextAlignmentCenter];

    // コンテキストから画像オブジェクトを作成する。
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;
}

NSStringクラスのインスタンスメソッドsizeWithFont:constrainedToSize:は文字列の描画領域のサイズをあらかじめ算出しておくのに便利だ。文字列の長さやフォントに応じてラベルのサイズなどの調整を行いたいときにも使える。