3

I'm trying to draw a simple shape as part of the interface of a game, and most tutorials use a UIBezierPath to define the path of a CAShapeLayer. However, I noticed that UIBezierPath already has an existing fill function.

This is probably a stupid question, but what is the difference between using that and using a separate CAShapeLayer to draw the path? Also, which one is better?

Léo Natan
  • 56,823
  • 9
  • 150
  • 195
MysteryPancake
  • 1,365
  • 1
  • 18
  • 47

1 Answers1

13

The "CA" in CAShapeLayer stands for CoreAnimation.

If you wish to animate, move, manipulate, or well, anything else to a UIBezierPath, you need to use a CALayer (or it's subclass CAShapeLayer).

UIBezierPaths are the correct thing to use if what you want is to simply "draw" - and it's usually done in draw(rect:). You can also "redraw" if you will.

But if you want persistence (and control) over a shape, turn that UIBezierPath into a CAShapeLayer.

  • What if we want to fill the uibezierpath with color and render it? isn't CAShapeLayer our only choice? @dfd – Reza.Ab Jan 31 '18 at 15:42
  • 1
    I think the most accurate answer is "it depends". You didn't use - or to me imply using - the word *animate*, so I'd say "no". All views have a `draw(rect:)` function you can override, containing a context you can draw a `UIBezierPath` in. This path can have a *stroke* and a *fill* color. And if you choose to *close* the bezier path it will fill the enclosed path with the fill color. Yes, that's a few things that can happen - and a `CAShapeLayer` gives you a layer that can be animated, but it isn't the *only* choice. –  Jan 31 '18 at 16:21
  • I understand, I mean I asked that since when i make a shape from path by CAshapelayer its so easy to render it exactly but using cgcontextref can sometimes be a nightmare. Which is why I'm stuck in this https://stackoverflow.com/q/48599949/3124848 @dfd I'd really appreciate it if you could guid me. – Reza.Ab Feb 04 '18 at 16:09