iOSプログラミング with Swift 2


2016.06.18: created by

SwiftでCoreGraphicsを使う(自由に描画したUIImageを生成する)

2Dグラフィックスを手軽に使うための方法が CoreGraphics です。

下の例では、自分が指定した大きさの Graphicsコンテクストを設定し、 線や曲線や文字を描画したあと、 最終的に新しい UIImage を作成しています。

  1. Xcode を起動して "Create a new Xcode project" で "Single View Application" として新しいプロジェクトを開きます。 ここではプロジェクト名を SwiftCoreGraphics としています。



  2. Main.storyboard上の ViewController の上に、ウィンドウ右下の "Object library" から "Image View" をドラッグして配置します。



  3. Image View を Outlet でViewController.swift中の "myImageView" 変数とconnectします。






  4. ViewController.swift を変更します。
  5. MyCGView.swiftに追加するコード(赤字部分)
    import UIKit
    
    class ViewController: UIViewController {
        
        @IBOutlet weak var myImageView: UIImageView!
        
        func makeUIImage() -> UIImage {
            UIGraphicsBeginImageContext(CGSizeMake(300,300))
            let context: CGContextRef = UIGraphicsGetCurrentContext()!
            
            CGContextSetRGBFillColor(context, 0.0, 1.0, 0.0, 1.0)
            CGContextAddRect(context, CGRectMake(20,20,50,50))
            CGContextFillPath(context)
            
            CGContextSetLineWidth(context, 5.0)
            CGContextSetRGBStrokeColor(context, 1.0, 0.0, 0.5, 1.0)
            CGContextAddRect(context, CGRectMake(30,30,70,70))
            CGContextStrokePath(context)
            
            CGContextSetLineWidth(context, 2)
            CGContextSetRGBStrokeColor(context, 0.0, 0.0, 1.0, 1.0)
            CGContextMoveToPoint(context, 15, 70)
            CGContextAddLineToPoint(context, 280, 200)
            CGContextStrokePath(context)
     
            let attrString = NSAttributedString(
                string: "漢字abc",
                attributes:[NSForegroundColorAttributeName: UIColor.greenColor(),
                    NSFontAttributeName: UIFont.boldSystemFontOfSize(20.0)])
            attrString.drawAtPoint(CGPointMake(40, 70))
            
            let img = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return img
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
            myImageView.image = makeUIImage()
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
        }
    
    }
    
  6. 実行すると以下の画面が表示される。


  7. サンプルのプロジェクトはこちら。(Xcode 7.3.1版)


http://nw.tsuda.ac.jp