Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CAGradientLayer for an angle / circle gradient

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.

like image 653
Max Avatar asked Mar 06 '14 10:03

Max


2 Answers

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)
like image 105
Erik Avatar answered Nov 03 '22 23:11

Erik


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.

like image 3
Duncan C Avatar answered Nov 03 '22 22:11

Duncan C