LoginSignup
51
47

More than 5 years have passed since last update.

[Swift] 画像とテキストを合成

Last updated at Posted at 2014-11-30

Swiftで画像とテキストを合成するサンプルコード

コード

func drawText(image :UIImage) ->UIImage
{
    let text = "Some text.."

    let font = UIFont.boldSystemFontOfSize(32)
    let imageRect = CGRectMake(0,0,image.size.width,image.size.height)

    UIGraphicsBeginImageContext(image.size);

    image.drawInRect(imageRect)

    let textRect  = CGRectMake(5, 5, image.size.width - 5, image.size.height - 5)
    let textStyle = NSMutableParagraphStyle.defaultParagraphStyle().mutableCopy() as NSMutableParagraphStyle
    let textFontAttributes = [
        NSFontAttributeName: font,
        NSForegroundColorAttributeName: UIColor.whiteColor(),
        NSParagraphStyleAttributeName: textStyle
    ]
    text.drawInRect(textRect, withAttributes: textFontAttributes)

    let newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext()

    return newImage
}

実行結果

スクリーンショット 2014-11-30 18.45.17.png

参考リンク

51
47
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
51
47