2015年5月6日水曜日

Core Animation Lesson.(カスタム描画/Lesson1-7)

Core Animation Lesson.(Lesson1-7)
カスタム描画.(Lesson1-7)

CALayerのcontentsプロパティを設定するとこだけが背景画像を描画する方法では有りません。UIViewのdrawRectメソッドを実装する事でCoreGraphicsやUIKitを利用し、ダイレクトに背景画像を描画することができます。drawRectメソッドにはデフォルト実装が有りませんが、Viewが最初に表示された時に一度呼び出され、以降は更新が必要になった場合に自動的に呼び出されます。明示的に再描画が必要な時はsetNeedsDisplayを呼び出す事で再描画が行われますので、再描画したいからといってコード内からdrawRectメソッドを直接呼び出してはいけません。

drawRectメソッドの実装

UIViewクラスを継承した新しいクラスを作成し、Storyboard上でViewを配置しCustomクラスとして新しく作成したクラスを指定します。

図. カスタムクラスの設定
drawRectメソッドでは、青色に塗りつぶされた楕円を描画するコードになっています。(以下コード)
  1. class Lesson1_7View: UIView {
  2.  
  3. // custom draw
  4. override func drawRect(rect: CGRect) {
  5. // get context
  6. let context: CGContext! = UIGraphicsGetCurrentContext()
  7. // draw with context
  8. // set fill color
  9. CGContextSetFillColorWithColor(context, UIColor.blueColor().CGColor)
  10. // draw ellpise in rect
  11. CGContextFillEllipseInRect(context, rect)
  12.  
  13. }
  14. }
図. カスタム描画
独自に追加したレイヤへのカスタム描画

CALayerにはdelegateプロパティが存在します。それがCALayerDelegateで、displayLayerとdrawLayer メソッドが定義されています。iOSの場合はUIViewを新たに作成するとCALayerも必ず生成されます。この予め生成されているCALayerの場合はUIView側でCALayerDelegateが実装されているため、改めて個別に実装する必要はありません。素直にdrawRectメソッドを実装すれば良いでしょう。

逆に新たに作成したCALayerでカスタム描画したい場合にCALayerDelegateを実装する必要があります。因みに、CALayerDelegateはCALayerクラスにNSObjectのエクステンション(カテゴリ)で定義されており、リファレンスにはInformal Protocolと表現されています。ですので、明示的にCALayerDelegateを採用するコード(クラス定義)を書く必要は無いようです。

  1. extension NSObject {
  2. /* If defined, called by the default implementation of the -display
  3. * method, in which case it should implement the entire display
  4. * process (typically by setting the `contents' property). */
  5. func displayLayer(layer: CALayer!)
  6. /* If defined, called by the default implementation of -drawInContext: */
  7. func drawLayer(layer: CALayer!, inContext ctx: CGContext!)
  8. /* Called by the default -layoutSublayers implementation before the layout
  9. * manager is checked. Note that if the delegate method is invoked, the
  10. * layout manager will be ignored. */
  11. func layoutSublayersOfLayer(layer: CALayer!)
  12. /* If defined, called by the default implementation of the
  13. * -actionForKey: method. Should return an object implementating the
  14. * CAAction protocol. May return 'nil' if the delegate doesn't specify
  15. * a behavior for the current event. Returning the null object (i.e.
  16. * '[NSNull null]') explicitly forces no further search. (I.e. the
  17. * +defaultActionForKey: method will not be called.) */
  18. func actionForLayer(layer: CALayer!, forKey event: String!) -> CAAction!
  19. }
コード. CALayerクラス内にあるエクステンション定義(Swift)

CALayerはdelegateが設定されているかを調べます。そして、設定されている場合はdisplayLayerメソッドが実装されているか確認します。実装されている場合は呼び出しを行い、もしdisplayLayer実装されていなかった場合はさらにdrawLayerメソッドが実装されているか確認し、実装されている場合はdrawLayerメソッドを呼び出します。
要するに、displayLayer → drawLayer の順で呼び出されるわけですが、displayLayerが実装されている場合はdrawLayerが実装されていても、呼び出されませんので注意が必要です。

新たにCALayerを作成して、そのレイヤをカスタム描画してみます。新たに作成したレイヤには赤色の円を描いています。

図. 独自に追加したレイヤのカスタム描画
  1. class Lesson1_7ViewController: UIViewController {
  2. @IBOutlet weak var myView: Lesson1_7View!
  3. private var newLayer: CALayer!
  4.  
  5. override func viewDidLoad() {
  6. super.viewDidLoad()
  7.  
  8. // Do any additional setup after loading the view.
  9. // create new layer
  10. newLayer = CALayer()
  11. newLayer.frame = CGRectMake(0, 0, 100, 100)
  12. newLayer.contentsScale = UIScreen.mainScreen().scale
  13. // set delegate
  14. newLayer.delegate = self
  15. // add new layer to uiview hosted layer
  16. myView.layer.addSublayer(newLayer)
  17. // display new layer
  18. newLayer.display()
  19. }
  20. override func viewDidDisappear(animated: Bool) {
  21. // clean up
  22. newLayer.delegate = nil
  23. }
  24.  
  25. override func didReceiveMemoryWarning() {
  26. super.didReceiveMemoryWarning()
  27. // Dispose of any resources that can be recreated.
  28. }
  29.  
  30. /***
  31. override func displayLayer(layer: CALayer!) {
  32. //
  33. }
  34. ***/
  35. override func drawLayer(layer: CALayer!, inContext ctx: CGContext!) {
  36. NSLog("perform drawLayer.")
  37. //
  38. CGContextSetFillColorWithColor(ctx, UIColor.redColor().CGColor)
  39. CGContextFillEllipseInRect(ctx, layer.frame)
  40. }
  41. }

以下コードが新しいレイヤを作成し、delegateを設定しています。

  1. // create new layer
  2. newLayer = CALayer()
  3. newLayer.frame = CGRectMake(0, 0, 100, 100)
  4. newLayer.contentsScale = UIScreen.mainScreen().scale
  5.  
  6. // set delegate
  7. newLayer.delegate = self

そして、以下がカスタムコード描画部分です。CGContextオブジェクトが引数にあるので、drawLayerメソッドの方を実装しています。drawLayerを呼び出したいため、displayLayerメソッドはコメントアウトにしています。

  1. override func drawLayer(layer: CALayer!, inContext ctx: CGContext!) {
  2. NSLog("perform drawLayer.")
  3. //
  4. CGContextSetFillColorWithColor(ctx, UIColor.redColor().CGColor)
  5. CGContextFillEllipseInRect(ctx, layer.frame)
  6. }



今回使用したサンプルプログラムはGithub上のCoreAnimationLessonに置いています。


AD.

0 件のコメント :

コメントを投稿