Rotation And Gradient in CoreGraphics and context - ios

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.

Related

How to apply color filter to a view

I've been trying to wrap my head around Core Image filters & layers but I couldn't find a solution to what I'm trying to achieve.
So I'm building an app which has a component where the user needs to draw over random shapes (here the shape is a circle for the sake of simplicity). When the user goes over the edge of the shape the stroke color must change from yellow to red.
what I'm trying to get
And this is what I have so far:
what I have
Here's how I set the "mask":
#IBOutlet private weak var tempImageView: UIImageView! {
willSet {
let maskImage: UIImage = UIImage(named: "circle2")!
let mask = CALayer()
mask.opacity = 0.8
mask.contents = maskImage.cgImage
mask.contentsGravity = CALayerContentsGravity.resizeAspect
mask.bounds = CGRect(x: 0,
y: 0,
width: newValue.frame.width,
height: newValue.frame.height)
mask.anchorPoint = CGPoint(x: 0, y: 0)
mask.position = CGPoint(x: 0, y: 0)
newValue.layer.addSublayer(mask)
}
}
and here's where I render the drawing:
func drawLine(from fromPoint: CGPoint, to toPoint: CGPoint) {
UIGraphicsBeginImageContext(view.frame.size)
guard let context = UIGraphicsGetCurrentContext() else {
return
}
tempImageView.image?.draw(in: view.bounds)
context.setLineCap(.round)
context.setBlendMode(.normal)
context.setLineWidth(brushWidth)
context.move(to: fromPoint)
context.setStrokeColor(UIColor.red.cgColor)
context.addLine(to: toPoint)
context.strokePath()
tempImageView.image = UIGraphicsGetImageFromCurrentImageContext()
tempImageView.alpha = 1.0
UIGraphicsEndImageContext()
}
However all this does is it fades the red color when inside the shape instead of giving it a different color, which I haven't been able to figure out how to do.

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.

equivalent way drawing method to UIGraphicsGetCurrentContext

I have a swift class that outputs pie chart, I want to take out drawing logic out of drawRect method, since UIGraphicsGetCurrentContext returns nil outside of the draw method I need to change way of drawing my pie chart view,
What is the appropriate way to do this? My PieChart class looks like;
override func draw(_ rect: CGRect) {
let context: CGContext = UIGraphicsGetCurrentContext()!
drawLinearGradient(context)
drawCenterCircle(context)
let circle: CAShapeLayer = drawStroke()
let pathAnimation = CABasicAnimation(keyPath: "strokeEnd")
pathAnimation.duration = percentage
pathAnimation.toValue = percentage
pathAnimation.isRemovedOnCompletion = rendered ? false : (percentageLabel > 20 ? false : true)
pathAnimation.isAdditive = true
pathAnimation.fillMode = kCAFillModeForwards
circle.add(pathAnimation, forKey: "strokeEnd")
}
private func drawLinearGradient(_ context: CGContext) {
let circlePoint: CGRect = CGRect(x: 0, y: 0,
width: bounds.size.width, height: bounds.size.height)
context.addEllipse(in: circlePoint)
context.clip()
let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceRGB()
let colorArray = [colors.0.cgColor, colors.1.cgColor]
let colorLocations: [CGFloat] = [0.0, 1.0]
let gradient = CGGradient(colorsSpace: colorSpace, colors: colorArray as CFArray, locations: colorLocations)
let startPoint = CGPoint.zero
let endPoint = CGPoint(x: 0, y: self.bounds.height)
context.drawLinearGradient(gradient!,
start: startPoint,
end: endPoint,
options: CGGradientDrawingOptions.drawsAfterEndLocation)
}
private func drawCenterCircle(_ context: CGContext) {
let circlePoint: CGRect = CGRect(x: arcWidth, y: arcWidth,
width: bounds.size.width-arcWidth*2,
height: bounds.size.height-arcWidth*2)
context.addEllipse(in: circlePoint)
UIColor.white.setFill()
context.fillPath()
}
private func drawStroke() -> CAShapeLayer {
let circle = CAShapeLayer()
self.layer.addSublayer(circle)
return circle
}
You can change your code to produce a UIImage containing the pie chart, and then place that image inside an image view:
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()
// ... here goes your drawing code, just as before
let pieImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let pieView = UIImageView(image: pieImage)
Note that if you need to update the chart very frequently (multiple times per second), this solution might bring a performance penalty because the image creation takes a bit more time then the pure rendering.

CALayer sublayer shows up but context drawing within it not working

I created a custom UIView class where I override the draw(_ rect: CGRect) function. In it, I added a gradient (CAGradientLayer) sublayer (which works without much problem) and then add another sublayer above it, a custom 'CloseLayer' class that inherits from CALayer.
That second sublayer I add gets correctly added in front with the right dimensions, however the line drawing I implemented in the draw(in ctx: CGContext) function of the custom CALayer class doesn't seem to be doing anything. I have been looking at several resources and googling for the past few days and am started to get a bit discouraged. Below is my code for the UIView class (that contains the two sublayers) and the custom layer class I want drawing to occur in. Any help is much appreciated!
class GraphAView: UIView {
// trading 9:00AM EST to 6:00PM EST
// Normal: 9:30AM EST to 4:00PM EST
// 9 hours total, 5 min intervals (12 intervals per hour, 108 total)
let HonchoGreyComponents : [CGFloat] = [0.2,0.2,0.2,1.0]
let graphBackGreyComponents: [CGFloat] = [0.8,0.8,0.8,1.0]
override func draw(_ rect: CGRect) {
setUpBack()
}
func setUpBack(){
let RGBSpace = CGColorSpaceCreateDeviceRGB()
let HonchoGrey = CGColor(colorSpace: RGBSpace, components: HonchoGreyComponents)
let graphBackGrey = CGColor(colorSpace: RGBSpace, components: graphBackGreyComponents)
let Gradlayer = CAGradientLayer()
Gradlayer.frame = self.bounds
Gradlayer.colors = [HonchoGrey!,graphBackGrey!,graphBackGrey!,HonchoGrey!]
//layer.locations = [NSNumber(value: PreMarketEnd),NSNumber(value: RegMarketEnd)]
Gradlayer.locations = [0,0.055555, 0.7777777]
Gradlayer.startPoint = CGPoint(x: 0, y: 0)
Gradlayer.endPoint = CGPoint(x: 1, y: 0)
self.layer.insertSublayer(Gradlayer, at: 0)
let closingLay = CloseLayer()
closingLay.frame = self.bounds
let yer = UIColor(red: 0.3, green: 0.6, blue: 0.8, alpha: 1.0)
//closingLay.backgroundColor = UIColor.blue.cgColor
//closingLay.backgroundColor = UIColor(white: 0.4, alpha: 0.0).cgColor
closingLay.backgroundColor = yer.cgColor
self.layer.insertSublayer(closingLay, above: Gradlayer)
closingLay.setNeedsDisplay()
self.layer.setNeedsDisplay()
}
}
class CloseLayer: CALayer {
let ClosinglineWidth: CGFloat = 4.0
let dashPattern: [CGFloat] = [2,2]
override func draw(in ctx: CGContext) {
let CloseContext = UIGraphicsGetCurrentContext()
let middleY = self.frame.height / 2
// let width = self.frame.width
// let context = UIGraphicsGetCurrentContext()
CloseContext?.setLineWidth(ClosinglineWidth)
CloseContext?.setLineDash(phase: 1, lengths: dashPattern)
CloseContext?.move(to: CGPoint(x: 0, y: middleY))
CloseContext?.addLine(to: CGPoint(x: self.frame.width, y: middleY)) // 358 width
let closingLineColor = UIColor.red.cgColor
CloseContext?.setStrokeColor(closingLineColor)
CloseContext?.strokePath()
}
func drawLine(start: CGPoint, end: CGPoint){
}
}
The problem is this line:
let CloseContext = UIGraphicsGetCurrentContext()
There is no current context. Your job is to draw into ctx, the context you were handed.
Long story short, change that line to:
let CloseContext : CGContext? = ctx
...and bingo, you will see your line. (But that is just for instant gratification. In the end, you should get rid of CloseContext everywhere and subsitute ctx.)

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

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.

Resources