Swift - how to create a non-pixelated radial gradient? - ios

I'm trying to create a radial / circular gradient for my app.
I used a solution similar to the confirmed answer here
However, the resulting gradient looks pixelated.
What am I doing wrong? Is there are more modern way or a good 3rd party framework to create smooth, simple radial gradients?
Thanks!
My code (based on snippets published on Stack Overflow):
class RadialGradientLayer: CALayer {
init(innerColor: UIColor, outerColor: UIColor) {
self.innerColor = innerColor.CGColor
self.outerColor = outerColor.CGColor
super.init()
needsDisplayOnBoundsChange = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
var innerColor: CGColor
var outerColor: CGColor
override func drawInContext(ctx: CGContext) {
CGContextSaveGState(ctx)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let locations:[CGFloat] = [0.0, 1.0]
let colors = [innerColor, outerColor]
let gradient = CGGradientCreateWithColors(colorSpace, colors, locations)
let center = CGPoint(x: bounds.width / 2.0, y: bounds.height / 2.0)
let radius = min(bounds.width / 2.0, bounds.height / 2.0)
CGContextDrawRadialGradient(ctx, gradient, center, 0.0, center, radius, CGGradientDrawingOptions(rawValue: 0))
}
}

You need to make sure the CGContext is scaled for the devices screen.
Take a look at the answers to this question - CGContext and retina display
This will help you fix the issue.

Related

Apply Beveled Radial Gradient to UIView

I'm currently using the following code here
#IBDesignable class RadialGradientView: UIView {
#IBInspectable var outsideColor: UIColor = UIColor.red
#IBInspectable var insideColor: UIColor = UIColor.green
override func draw(_ rect: CGRect) {
let colors = [insideColor.cgColor, outsideColor.cgColor] as CFArray
let endRadius = sqrt(pow(frame.width/2, 2) + pow(frame.height/2, 2))
let center = CGPoint(x: bounds.size.width / 2, y: bounds.size.height / 2)
let gradient = CGGradient(colorsSpace: nil, colors: colors, locations: nil)
let context = UIGraphicsGetCurrentContext()
context?.drawRadialGradient(gradient!, startCenter: center, startRadius: 0.0, endCenter: center, endRadius: endRadius, options: CGGradientDrawingOptions.drawsBeforeStartLocation)
}
}
This code will draw a radial gradient that looks like this:
What I am trying to do is make it look like below (which is how it looks in the current desktop version of the app).
You will notice that in the desktop version the gradient has blue at the top and bottom and the white area is stretched to include more of the text area so it's easier to read.
How can I recreate this effect? I have tried for hours playing with different numbers and settings in the current code to no avail so far (such as changing the endRadius).
Any help or ideas are appreciated.

How to fix inconsistent color-to-clear radial gradient layer

When trying to draw a radial gradient from white to clear, I obtain different results depending on whether I use UIColor(white:alpha:), UIColor.white.withAlpha.Components(alpha:) or UIColor.color. How Can I get the same gradient with a clear color as with a plain color?
I order to draw a radial gradient, I have overridden the draw(context:) method (see below). My code seems to work fine when using plain colours for a gradient but works "mysteriously" when using a clear color.
override func draw(in ctx: CGContext) {
super.draw(in: ctx)
ctx.saveGState()
let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colorFill as CFArray, locations: self.locations as! [CGFloat] )
let startPoint = CGPoint(x: startX, y: startY )
let endPoint = CGPoint(x: endX , y: endY)
let drawingOption : CGGradientDrawingOptions = radius > 0 ? [] : .drawsAfterEndLocation
//self.masksToBounds = true
if gradientType == .radial {
ctx.drawRadialGradient(gradient!, startCenter: startPoint, startRadius: 0.0, endCenter: endPoint, endRadius: self.frame.width / 2, options: drawingOption)
} else {
self.startPoint = startPoint
self.endPoint = endPoint
}
}
Here's the results I obtain depending on the input colours for the gradient:
[UIColor.white.cgColor,UIColor.black.cgColor]
(desired result with clear color instead of black)
[UIColor.white.cgColor, UIColor.clear.cgColor]
[UIColor.white.cgColor, UIColor.white.withAlphaComponent(0.0).cgColor]
[UIColor(white: 0.0, alpha: 1).cgColor, UIColor(white: 1.0, alpha: 0).cgColor]
Could someone can explain why I don't get the same output as with only plain colours (output I wish to obtain)?
Thanks a lot for taking the time to read and reply!
The layer is not drawn only in the draw(in context:) method. This line of code confirms some properties had been set prior to the call of the method, which has priorly triggered the drawing of the layer (self.locations):
CGColorSpaceCreateDeviceRGB(), colors: colorFill as CFArray, locations: self.locations as! [CGFloat] )
By removing the set of self.colors and self.locations properties in the custom initializer and storing the values in Type Properties instead before calling self.setNeedDisplay(), the layer is only being drawn in the draw(in context:) method.
class CustomLayer {
override init() {
super.init()
needsDisplayOnBoundsChange = true
}
override init(layer: Any) {
super.init(layer: layer)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var colors = []()
var colorMap = [NSNumber]()
custom init() {
colors = [color,color]
colorMap = [0.0, 1.0]
self.setNeedDisplay()
}
override func draw(in ctx: CGContext) {
super.draw(in: ctx)
ctx.saveGState()
guard let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: colors as CFArray, locations: colorMap as! [CGFloat] ) else {return}
let startPoint = CGPoint(x: startX, y: startY )
let endPoint = CGPoint(x: endX , y: endY)
self.masksToBounds = true
if gradientType == .radial {
ctx.drawRadialGradient(gradient, startCenter: startPoint, startRadius: 0.0, endCenter: endPoint, endRadius: self.frame.width / 2, options: drawingOption)
} else {
self.locations = colorMap
self.colors = colors
self.startPoint = startPoint
self.endPoint = endPoint
}
}
}
Cheers!

Bad quality for my Radial Gradient

I am drawing a radial gradient in UIView's drawRect function which is pretty simple, the problem I have is that on device (iPhone 6S plus) gradient quality is pretty bad.
Do you have an idea why?
EDIT: I noticed that gradient is bad if my view or color has an alpha value less than 1.0.
private func updateGradient() {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let colors:[CGColor] = [haloColor.CGColor, UIColor.clearColor().CGColor]
gradient = CGGradientCreateWithColors(colorSpace, colors, [0.0,0.8])
setNeedsDisplay()
}
override public func drawRect(rect: CGRect) {
if let gradient = self.gradient {
let context = UIGraphicsGetCurrentContext()
let options: CGGradientDrawingOptions = [.DrawsAfterEndLocation]
let center = CGPoint(x: bounds.midX, y: -70)
CGContextDrawRadialGradient(context, gradient, center, 0, center, size.height*3, options)
}
}

Swift - Poor gradient quality in UIView size animation

I have the following structure in place:
main view contains subview1; subview1 is laid out using constraints
subview1 contains subview2; subview2 also has constraints and I need to animate the size of subview2
in subview2 I call CGContextDrawRadialGradient to draw a circle with a gradient
The code in subview1 is:
let circle = GradientCircle(frame: CGRect(origin: CGPointZero, size: frame.size), withColor: color)
addSubview(circle)
circle.centerXAnchor.constraintEqualToAnchor(centerXAnchor).active = true
circle.centerYAnchor.constraintEqualToAnchor(centerYAnchor).active = true
let widthConstraint = circle.widthAnchor.constraintEqualToConstant(frame.width * 3)
let heightConstraint = circle.heightAnchor.constraintEqualToConstant(frame.width * 3)
circle.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activateConstraints([heightConstraint, widthConstraint])
layoutIfNeeded()
UIView.animateWithDuration(3.0, delay: 0, options: [.Repeat], animations: {
widthConstraint.constant = 2
heightConstraint.constant = 2
self.layoutIfNeeded()
}, completion: nil)
Here's a gif to show what the problem is: http://i.stack.imgur.com/LWP7d.gif
Why does this drop in quality occur and how can I fix it? Obviously, I'm new in Swift and I don't fully understand the whole layout and animation thing, so please help if you can, it's slowly driving me insane :)
EDIT:
Here's the GradientCircle class (which is subview2 in the description above), maybe the problem is with how the gradient is drawn:
class GradientCircle : UIView {
var color: UIColor
init(frame: CGRect, withColor: UIColor) {
color = withColor
super.init(frame: frame)
backgroundColor = UIColor.clearColor()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
let locations: [CGFloat] = [0.0, 1.0]
let colorspace = CGColorSpaceCreateDeviceRGB()
let colors = [color.CGColor, GraphicsUtils.darkGrayColor().CGColor]
let gradient = CGGradientCreateWithColors(colorspace, colors, locations)
let startPoint = CGPoint(x: rect.width / 2, y: rect.height / 2)
let endPoint = CGPoint(x: rect.width / 2, y: rect.height / 2)
let startRadius: CGFloat = 0
let endRadius: CGFloat = rect.width / 2
CGContextClearRect(context, rect)
CGContextDrawRadialGradient(context, gradient, startPoint, startRadius, endPoint, endRadius, CGGradientDrawingOptions.DrawsAfterEndLocation)
}

Rotation And Gradient in CoreGraphics and context

I'm definitely missing some parts of Core Graphics context and cannot clear things out by myself.
Here is my code in Xcode Playground
import UIKit
class MyView08 : UIView {
override func drawRect(rect: CGRect) {
let cornerRaduis : CGFloat = 20
let pathRect = CGRectInset(self.bounds, 20, 20)
let rectanglePath = UIBezierPath(roundedRect: pathRect, cornerRadius: cornerRaduis)
var context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
rotate(rectanglePath, context: context)
CGContextRestoreGState(context)
context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
// drawGrad(rectanglePath, context: context)
CGContextRestoreGState(context)
}
func rotate(rectanglePath : UIBezierPath, context : CGContext) {
let rotation = CGAffineTransformMakeRotation(CGFloat(M_PI) / 4.0)
CGContextConcatCTM(context, rotation)
UIColor.greenColor().setFill()
rectanglePath.fill()
}
func drawGrad (rectanglePath : UIBezierPath, context : CGContext) {
let startColor = UIColor.redColor()
let endColor = UIColor.greenColor()
let gradientColors : CFArray = [startColor.CGColor, endColor.CGColor]
let gradientLocations : [CGFloat] = [0.0, 1.0]
let colorSpace = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradientCreateWithColors(colorSpace, gradientColors, gradientLocations)
let topPoint = CGPointMake(self.bounds.size.width / 2, 20)
let bottomPoint = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height - 20)
rectanglePath.addClip()
CGContextDrawLinearGradient(context, gradient, bottomPoint, topPoint, 0)
}
}
let myViewRect = CGRect(x: 0, y: 0, width: 300, height: 300)
let myView = MyView08(frame: myViewRect)
If i uncomment this line
drawGrad(rectanglePath, context: context)
Everything is going bad, Xcode trying to execute code almost 2 thousands times and after that it fails.
I'm trying to rotate rectangle and draw a gradient.
You are experiencing an infinite recursion. I don't know why, but it has to do with your testing procedure. The problem lies in how you are testing - not in your code. Don't test this kind of code in a playground. Playgrounds are not reality.
(I could generalize and say, don't use playgrounds ever. They are the work of the devil. But I'm not going to. Ooops, did I say that out loud?)
Anyway, I copied and pasted your code into a fresh app project (and I uncommented the drawGrad line), and it ran just fine with no recursion issues of the kind you describe.
Note that you will need to put your view into the interface in order for it to do anything. I added this line in order to do that:
self.view.addSubview(myView)
Apart from that, my code is identical to yours, and there's no problem.

Resources