8

How can I use a CAGradientLayer to most efficiently draw a gradient around a circle / with angles?

I made the one underneath with the help of this project. It uses a bitmap context for drawing but a CAGradientLayer would be far more efficient.

Unfortunately I could only figure out how to make linear gradients with it.

Rajesh
  • 10,318
  • 16
  • 44
  • 64
Max
  • 2,699
  • 2
  • 27
  • 50

2 Answers2

11

I realize many years have passed since this question was asked, but for anybody who stumbles across it now, iOS 12 added a conic gradient type that makes this possible.

gradientLayer.type = CAGradientLayerType.conic
gradientLayer.frame = bounds
gradientLayer.colors = [startColor.cgColor, endColor.cgColor]
gradientLayer.startPoint = CGPoint(x: 0.5, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 0.5, y: 0)
Erik
  • 2,299
  • 4
  • 18
  • 23
3

Gradient layers currently only support linear gradients. However, if you look at the interface for gradient layers, it includes a type property. Right now the only type defined is kCAGradientLayerAxial (linear).

The fact that there is a type property suggests that Apple will be adding more types at some future date, and radial gradients seem like a very like addition.

You might look at creating your own custom subclass of CAGradientLayer that draws radial gradients as well as linear. I've seen demo projects on the net that create custom CALayer subclasses.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Hey thank you for the response, yeah the project that I linked above creates a subclass of CALayer to render the angular gradient that I showed above. Unfortunately this is rather slow since it's drawing to a CGBitmapContext. – Max Mar 08 '14 at 15:43
  • 1
    Unfortunately kCAGradientLayerAxial has been the only supported gradient type since when it was introduced. So even though we can assume that support for other types of gradients will be added at some point, I don't it will happen any time soon. – David Rönnqvist Mar 08 '14 at 15:45
  • 1
    Core Graphics has the CGContextDrawRadialGradient method. Time to implement a custom subclass of CAGradientLayer that supports your own gradient type. You can implement drawInContext:and call CGContextDrawRadialGradient. It should only take a few lines of code, and a couple of extra properties on the layer, to implement. – Duncan C Mar 08 '14 at 18:19