Masking a CAShapeLayer creates this weird artifact? - ios

I want to create a smooth progress bar for a to-do list. I used a circle (CGMutablePath) that masks the gray area and there's an obvious arc-like artifact. Not only that but there's also an artifact on the right side of the bar.
Note: I tried to rasterize the layers to no avail.
What causes iOS to do this and how can I smooth this out or get rid of it?
private var circleMask: CAShapeLayer = CAShapeLayer()
override func layoutSubviews() {
super.layoutSubviews()
backgroundColor = GradientColor(.leftToRight, frame: self.bounds, colors: GradientFlatRed())
layer.cornerRadius = bounds.height / 2
plainProgressBar.layer.cornerRadius = layer.cornerRadius
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
plainProgressBar.layer.shouldRasterize = true
plainProgressBar.layer.rasterizationScale = UIScreen.main.scale
createMask()
}
private func createMask() {
let path = CGMutablePath()
path.addArc(center: CGPoint(x: bounds.origin.x+25/2, y: bounds.origin.y+25/2), radius: 25/2, startAngle: 0, endAngle: CGFloat(Double.pi*2), clockwise: false)
path.addRect(bounds)
circleMask.path = path
circleMask.backgroundColor = plainMeterColor.cgColor
circleMask.fillRule = kCAFillRuleEvenOdd
plainProgressBar.layer.mask = circleMask
}

The issue is clearly an error in composition of the antialiased edges.
Knee-jerk question: do you have an atypical blend mode set?
Easiest solution: don't use path.addArc and path.addRect to generate two completely distinct shapes. Just use one of the init(roundedRect:... methods and set a corner radius of half your height, stretching the total path beyond the available space to the left to create a hard edge.
Or, if that doesn't appear, construct the path manually as a move, addLine(to:, addArc of only half a circle, then a final addLine(to: and a close. E.g. (thoroughly untested, especially re: start and end angles and clockwise versus anticlockwise versus iOS's upside-down coordinate system)
private func createMask() {
let path = CGMutablePath()
path.move(to: CGPoint(x: 0, y:0))
path.addLine(to: CGPoint(x: bounds.origin.x+25/2, y: 0))
path.addArc(center: CGPoint(x: bounds.origin.x+25/2, y: bounds.origin.y+25/2), radius: 25/2, startAngle: CGFloat(Double.pi/2.0), endAngle: CGFloat(Double.pi*3.0/2.0), clockwise: false)
path.addLine(to: CGPoint(x: 0, y: 25))
path.close()
...

Related

Why does CAShapeLayer exist?

I'm trying to understand CAShapeLayer and where it shines. It seems like the main advantage is the shape style properties that you can conveniently access:
let shapeLayer = CAShapeLayer()
shapeLayer.frame = CGRect(origin: CGPoint(x: 100, y: 100), size: .init(width: 200, height: 200))
shapeLayer.fillColor = .none
shapeLayer.lineWidth = 5
shapeLayer.strokeColor = UIColor.blue.cgColor
let path = UIBezierPath()
let withCenter = CGPoint(x: 100, y: 100)
let radius = CGFloat(100)
let startAngle = CGFloat(0.0)
let endAngle = CGFloat(CGFloat.pi * 2)
path.addArc(withCenter: withCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
shapeLayer.path = path.cgPath
But, I think the advantage ends there. It rather limits your ability set the context to multiple states like colors for different paths and requires a new CAShapeLayer. I can override the drawing method or use the delegate, but that's be doing the same thing as CALayer in that case.
On the other hand, with CALayer:
let layer = CALayer()
layer.frame = CGRect(origin: CGPoint(x: 100, y: 300), size: .init(width: 200, height: 200))
let renderer = UIGraphicsImageRenderer(size: CGSize(width: 200, height: 200))
let image = renderer.image { (_) in
let path = UIBezierPath()
let withCenter = CGPoint(x: 100, y: 100)
let radius = CGFloat(100)
let startAngle = CGFloat(0.0)
let endAngle = CGFloat(CGFloat.pi * 2)
path.lineWidth = 5
UIColor.blue.setStroke()
path.addArc(withCenter: withCenter, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
path.stroke()
}
layer.contents = image.cgImage
you can set multiple stroke colors for different paths. Obviously, you can set the CAShapeLayer's contents in a similar manner, but I want to take advantage of CAShapeLayer's API's that CALayer doesn't offer.
Are the shape style properties the main reason for CAShapeLayer?
For me, the big advantage to CAShapeLayer is animation. As Matt says, you can animate strokeStart and/or strokeEnd to cause a shape to either appear like it's being drawn with a pen, or disappear. You can also use animate strokeStart and/or strokeEnd to create a variety of different "wipe" animations.
Here is a link to a post I wrote using animations to strokeEnd to create a "clock wipe" animation:
How do you achieve a "clock wipe"/ radial wipe effect in iOS?
You can also animate the path that's installed into the shape layer. As long as the starting and ending paths have the same number of control points, the system creates a smooth, elegant looking animation. There are some tricks to making this work correctly however. Arc animations don't work as expected if you change the arc angle during an animation, because internally arcs are composed of different numbers of cubic Bezier curves.
Check out my projects RandomBlobs and TrochoidDemo on Github for examples of animating a path's control points.

Swift: addLine ignored in between two addArc calls when creating a path

This code does what I expect. It draws an arc, then adds a line 50 points wide from the top of that arc:
path.move(to: .init(x: myX, y: myY))
path.addArc(withCenter: CGPoint(x: centerX, y: centerY), radius: radius1, startAngle: .pi, endAngle: (3 * .pi)/2, clockwise: true)
let currentPoint = path.currentPoint
path.addLine(to: CGPoint(x: currentPoint.x + 50, y: currentPoint.y))
This code ignores the addLine for adding a 50 points wide line and just starts the second arc right at the top of the first arc.
path.move(to: .init(x: myX, y: myY))
path.addArc(withCenter: CGPoint(x: centerX, y: centerY), radius: radius1, startAngle: .pi, endAngle: (3 * .pi)/2, clockwise: true)
let currentPoint = path.currentPoint
path.addLine(to: CGPoint(x: currentPoint.x + 50, y: currentPoint.y))
path.addArc(withCenter: CGPoint(x: centerX + 50, y: centerY), radius: radius1, startAngle: (3 * .pi)/2, endAngle: .pi, clockwise: false)
With this second bit of code, I get the exact same output if I comment out the addLine code. I get the exact same output if I change the addLine code to add 300 pixels points instead of 50. The addLine code is ignored and I get two arcs, without a line between where the first ends and the second begins.
Any suggestions? Thanks so much!
You said:
With this second bit of code, I get the exact same output if I comment out the addLine code.
Yep, when you add an arc to an existing path, it will automatically draw a line from the currentPoint to the start of this second arc. If you don’t want it to add the line in between, you need to do a move(to:) in your path to where the second arc will start if you don’t want the line in-between. Or create two paths, one for each arc, and stroke them separately.
I get the exact same output if I change the addLine code to add 300 pixels instead of 50.
That doesn’t quite make sense and I cannot reproduce that behavior. For example, this is what I get when I move the second arc 50pt (and I’ll animate the stroke so you can see what’s going on):
But this is what I get when I move the line 300pt (but keep the second arc only 50pt from the first):
Clearly, if you not only make the line 300pt long, but move the center of the second arc by 300pt as well, then it will be just like the first example (except further apart).
However, if I replace your addLine(to:) with move(to:), then you won’t get the line in-between them:
FWIW, in all of these examples, I didn’t know what you were using for myX and myY, so I used a point to the left of the first arc. Clearly, if you don’t want that extra line, move myX and myY to the start of the first arc (or just comment that out entirely).
i dont know whats wrong with your code but have what i have tried .. it might help you thats why posting it
#IBDesignable
class CustomBg:UIView {
private lazy var curvedLayer: CAShapeLayer = {
let shapeLayer = CAShapeLayer()
shapeLayer.fillColor = UIColor.yellow.cgColor
shapeLayer.lineWidth = 4
shapeLayer.strokeColor = UIColor.green.cgColor
return shapeLayer
}()
//MARK:- inializer
override init(frame: CGRect) {
super.init(frame: frame)
layer.addSublayer(curvedLayer)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
layer.addSublayer(curvedLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
updatePath()
}
func updatePath() {
let centerX = 100
let centerY = 100
let radius1 = CGFloat( 50.0)
let path = UIBezierPath()
path.addArc(withCenter: CGPoint(x: centerX, y: centerY), radius: radius1, startAngle:0, endAngle: (2 * .pi), clockwise: true)
let currentPoint = path.currentPoint
path.addLine(to: CGPoint(x: currentPoint.x + 150, y: currentPoint.y))
path.addArc(withCenter: CGPoint(x: Int(path.currentPoint.x + radius1) , y: centerY), radius: radius1 , startAngle: .pi, endAngle: (3 * .pi ), clockwise: true)
curvedLayer.path = path.cgPath
}
}

Swift: UIBezierPath fill intersection of 2 paths

I'm working with 2 UIBezierPath to create a rectangle and a semicircle shape. It works fine but I am not able to fill the intersection with color.
That's my drawCircle and my addPaths functions:
private func drawCircle(selectedPosition: SelectionRangePosition, currentMonth: Bool) {
circleView.layer.sublayers = nil
let radius = contentView.bounds.height/2
let arcCenter = CGPoint(x: ceil(contentView.bounds.width/2), y: ceil(contentView.bounds.height/2))
let circlePath = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: .pi/2, endAngle: .pi * 3/2, clockwise: selectedPosition == .left)
let semiCircleLayerPath = UIBezierPath()
let semiCircleLayer = CAShapeLayer()
semiCircleLayer.fillColor = UIColor.tealish.cgColor
circleView.layer.addSublayer(semiCircleLayer)
switch (selectedPosition, currentMonth) {
case (.left, true):
let rectanglePath = UIBezierPath(rect: CGRect(x: contentView.bounds.width / 2, y: 0, width: ceil(contentView.bounds.width / 2), height: contentView.bounds.height))
addPaths(semiCircleLayerPath, rectanglePath, circlePath, semiCircleLayer)
case (.middle, true):
backgroundColor = .tealish
case (.right, true):
// Note: The + 10 is just to overlap the shapes and test if the filling works
let rectanglePath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: ceil(contentView.bounds.width / 2) + 10, height: contentView.bounds.height))
addPaths(semiCircleLayerPath, rectanglePath, circlePath, semiCircleLayer)
default:
backgroundColor = .clear
}
}
private func addPaths(_ semiCircleLayerPath: UIBezierPath, _ rectanglePath: UIBezierPath, _ circlePath: UIBezierPath, _ semiCircleLayer: CAShapeLayer) {
semiCircleLayerPath.append(circlePath)
semiCircleLayerPath.append(rectanglePath)
semiCircleLayer.path = semiCircleLayerPath.cgPath
}
The problem is that the semicircle path and the rectangle path are being added in opposite directions. This is a function of the way the Cocoa API adds them, unfortunately; in your case, it means that the intersection has a "wrap count" of 0.
Fortunately, there is an easy fix: create separate paths for the semicircle and the rectangle. When fill them both individually, you should get your desired result.
Unfortunately, this will mean that you can't use layer drawing only: you will want to use the drawRect method to draw the background.
If your dates are separate UILabels, you can skip this rendering & path filling problem entirely by dropping a UIView as a child of the calendar, under the labels holding the dates; give it a background color & rounded corners (using layer.cornerRadius as usual). That'll take care of your rounded rect for you.

How to centre a subview in UIView?

I am trying to create a timer. I have a circle using UIBezierPath which I will animate to show the time remaining. This is the code that draws the shape and adds it to the view:
func drawBgShape() {
bgShapeLayer.path = UIBezierPath(arcCenter: CGPoint(x: center.x , y: center.y), radius:
bounds.width/2, startAngle: -.pi/2, endAngle: 1.5*.pi, clockwise: true).cgPath
bgShapeLayer.strokeColor = UIColor.red.cgColor
bgShapeLayer.fillColor = UIColor.clear.cgColor
bgShapeLayer.lineWidth = 10
layer.addSublayer(bgShapeLayer)
}
However, when the code is run, it looks like this;
I have tried a number of ways to centre the progress bar but none of them seem to work. For example, using frame.height/2 doesn't have any effect.
How can I centre the progress bar?
Thanks.
EDIT:
bgShapeLayer is defined like this:
let bgShapeLayer = CAShapeLayer()
The issue is probably this phrase:
arcCenter: CGPoint(x: center.x , y: center.y)
A view center is where the view is located in its superview. That’s not what you want. You want the center of the view. Try this:
arcCenter: CGPoint(x: bounds.midX , y: bounds.midY)
However, it would be better if you gave your shape layer a frame, size, and position and did everything in terms of the shape layer (which is, after all, where the shape is being drawn). For example:
bgShapeLayer.frame = self.layer.bounds
self.layer.addSublayer(bgShapeLayer)
bgShapeLayer.path = UIBezierPath(
arcCenter: CGPoint(x: bgShapeLayer.bounds.midX, y: bgShapeLayer.bounds.midY),
radius: bgShapeLayer.bounds.width/2,
startAngle: -.pi/2, endAngle: 1.5*.pi, clockwise: true).cgPath
That way we do not confuse the view coordinates and the layer coordinates, as your code does. To some extent you can get away with this because it happens that in this situation there is a general equivalence of the view internal coordinates, its layer internal coordinates, and the bgShapeLayer internal coordinates, but such confusion is not a good habit to get into. You should say what you mean rather than relying on a contingency.

UIView pauses during animation along UIBezierPath

I'm trying to animate a UIView(a square) to move along a UIBezierPath using a CAKeyframeAnimation. The square pauses at two points along the bezier path, both points being right before the path begins to arc.This is my code for the UIBezierPath and Animation:
func createTrack() -> UIBezierPath {
let path = UIBezierPath()
path.move(to: CGPoint(x: layerView.frame.size.width/2, y: 0.0))
path.addLine(to: CGPoint(x: layerView.frame.size.width - 100.0, y: 0.0))
path.addArc(withCenter: CGPoint(x: layerView.frame.size.width - 100.0,y: layerView.frame.height/2), radius: layerView.frame.size.height/2, startAngle: CGFloat(270).toRadians(), endAngle: CGFloat(90).toRadians(), clockwise: true)
path.addLine(to: CGPoint(x: 100.0, y: layerView.frame.size.height))
path.addArc(withCenter: CGPoint(x: 100.0,y: layerView.frame.height/2), radius: layerView.frame.size.height/2, startAngle: CGFloat(90).toRadians(), endAngle: CGFloat(270).toRadians(), clockwise: true)
path.close()
return path
}
#IBAction func onAnimatePath(_ sender: Any) {
let square = UIView()
square.frame = CGRect(x: 55, y: 300, width: 20, height: 20)
square.backgroundColor = UIColor.red
layerView.addSubview(square)
let animation = CAKeyframeAnimation(keyPath: "position")
animation.path = trackPath.cgPath
animation.rotationMode = kCAAnimationRotateAuto
animation.repeatCount = Float.infinity
animation.duration = 60
square.layer.add(animation, forKey: "animate position along path")
}
layerView is just a UIView. Any ideas on why this happens and how I can fix this?
The path you are using consists of 5 segments (two arcs and three lines (including the one when you close the path)) and the animation spends the same time on each of the segments. If this path if too narrow, these lines segments will have no length and the square will appear still for 12 seconds in each of them.
You probably want to use a "paced" calculation mode to achieve a constant velocity
animation.calculationMode = kCAAnimationPaced
This way, the red square will move at a constant pace – no matter how long each segment of the shape is.
This alone will give you the result you are after, but there's more you can do to simplify the path.
The addArc(...) method is rather smart and will add a line from the current point to the start of the arc itself, so the two explicit lines aren't needed.
Additionally, if you change the initial point you're moving the path to to have the same x component as the center of the second arc, then the path will close itself. Here, all you need are the two arcs.
That said, if the shape you're looking to create is a rounded rectangle like this, then you can use the UIBezierPath(roundedRect:cornerRadius:) convenience initializer:
let radius = min(layerView.bounds.width, layerView.bounds.height) / 2.0
let path = UIBezierPath(roundedRect: layerView.bounds, cornerRadius: radius)

Resources