I can generate a square with this standard code.
func drawSquare() {
let width:CGFloat = 100
var square = UIBezierPath()
square.moveToPoint(CGPoint(x: 0, y: 0))
square.addLineToPoint(CGPoint(x: width, y: 0))
square.addLineToPoint(CGPoint(x: width, y: width))
square.addLineToPoint(CGPoint(x: 0, y: width))
square.lineWidth = 5
square.closePath()
UIColor.blackColor().setStroke()
square.stroke()
}
However, if I want to draw each addLineToPoint() segment in two steps, my square no longer draws correctly.
func drawSquare2Steps() {
let width:CGFloat = 200
let mult:CGFloat = 2
var square = UIBezierPath()
square.moveToPoint(CGPoint(x: 0, y: 0))
square.addLineToPoint(CGPoint(x: 100, y: 0)) // 1
square.addLineToPoint(CGPoint(x: 200, y: 0)) // 2
square.addLineToPoint(CGPoint(x: 200, y: 100)) // 3
square.addLineToPoint(CGPoint(x: 200, y: 200)) // 4
square.addLineToPoint(CGPoint(x: 100, y: 200)) // 5
square.addLineToPoint(CGPoint(x: 0, y: 200)) //6
square.lineWidth = 5
square.closePath() // 7
UIColor.orangeColor().setStroke()
square.stroke()
}
Here's the path that I see:
I tried to describe this function in this image:
My final goal isn't to draw a square but a more complicated path. The square simply illustrates the problem with my complex path.
Nothing is wrong except that your view size is (100, 100) but the square size is (200,200), so you don't see the whole square.
Related
There is new functionality in iOS 16 for CGPath (Core Graphics), more precisely there is a function intersection(_:using:) for determining the intersection of two CGPaths (see https://developer.apple.com/documentation/coregraphics/cgpath/3994964-intersection) and several related functions for union, normalization, separating a path into its components etc.
I tested several of them and nothing seems to work. In fact, any randomly composed non-trivial example gives me wrong results. For example, the following code gives me the first picture below: The purple area is the correct intersection.
var pathRedFill = CGMutablePath(rect: CGRect(origin: CGPoint(x: 10, y: 10),
size: CGSize(width: 400, height: 700)),
transform: nil)
pathRedFill.addQuadCurve(to: CGPoint(x: 267, y: 121), control: CGPoint(x: 395, y: 735))
pathRedFill.closeSubpath()
var pathBlueFill = CGMutablePath(rect: CGRect(origin: CGPoint(x: 120, y: 120),
size: CGSize(width: 200, height: 200)), transform: nil)
pathBlueFill.addQuadCurve(to: CGPoint(x: 637, y: 176), control: CGPoint(x: 343, y: 451))
pathBlueFill.closeSubpath()
context.setBlendMode(.normal)
context.setFillColor(red: 1, green: 0, blue: 0, alpha: 0.5)
context.addPath(pathRedFill)
context.drawPath(using: .eoFill)
context.setFillColor(red: 0, green: 0, blue: 1, alpha: 0.5)
context.addPath(pathBlueFill)
context.drawPath(using: .eoFill)
If I add the following code to calculate the intersection path, I get the second picture. The green line should exactely circle the purple area. But it does not.
context.setLineWidth(4)
context.setStrokeColor(red: 0, green: 1, blue: 0, alpha: 1)
let intersectionPath = pathRedFill.intersection(pathBlueFill, using: .evenOdd)
context.addPath(intersectionPath)
context.drawPath(using: .stroke)
My questions:
Is there something that I am doing wrong? (The documentation does not put any requirements on my two paths that I intersect, so my paths are not too complex I should think...)
Has anyone experienced similar bugs?
Thank you very much for your help!
EDIT:
I have done more tests of all the 10 functions added in iOS16 (with correcting the mistake in my path formulation according to DonMag), and tried to find the most simple case where I think something goes wrong. So this (all the other code stays the same, only the paths change)
let pathRedFill = CGPath(rect: CGRect(origin: CGPoint(x: 200, y: 300),
size: CGSize(width: 200, height: 200)),
transform: nil)
var pathBlueFill = CGMutablePath()
pathBlueFill.move(to: CGPoint(x: 302.854156, y: 369.438843))
pathBlueFill.addQuadCurve(to: CGPoint(x: 296.932526, y: 386.031342), control: CGPoint(x: 218.5, y: 376.0))
pathBlueFill.closeSubpath()
gives the result:
The green line should circle the purple but does not.
This first was part of an example where there were lots of self-intersections both for the red and for the blue path and I thought the self-intersections of the paths were the problem (since I had some other quite complex examples without self-intersections, but with holes, where everything seemed to go fine). But when I was done stripping to minimum, it turns out that there is something else at odds, as there is no more self-intersections in either path...
When rounding the numbers of the blue path, the error goes away, so it is this kind of degenerate corner case regarding the roots maybe... Also my blue curve is a quadratic (and then there is the line to close the path) whereas it turns out the intersection, stroked in green, is a cubic Bezier. I am not sure if I am still doing something wrong...
Several possibilities...
the new path intersection function (and maybe others) are a little "buggy"
it's working correctly, but our understanding of how the paths are built is a bit fuzzy
a combination of 1 & 2
After some experimentation, I get this with your original code on iOS (not sure why it's flipped vertically -- are you running this on MacOS app?):
Now, as I understand it, this line:
var pathRedFill = CGMutablePath(rect: CGRect(origin: CGPoint(x: 10, y: 10),
size: CGSize(width: 400, height: 700)),
transform: nil)
is equivalent to this:
var pathRedFill = CGMutablePath()
pathRedFill.move(to: CGPoint(x: 10, y: 10))
pathRedFill.addLine(to: CGPoint(x: 410, y: 10))
pathRedFill.addLine(to: CGPoint(x: 410, y: 710))
pathRedFill.addLine(to: CGPoint(x: 10, y: 710))
pathRedFill.closeSubpath()
The next thing we do is:
pathRedFill.addQuadCurve(to: CGPoint(x: 267, y: 121), control: CGPoint(x: 395, y: 735))
pathRedFill.closeSubpath()
And we get our expected output... but, when we complete the rest of the code we're getting (what appears to be) an incorrect intersection.
My guess is that there is some sort of "disconnect" when calling .addQuadCurve after the first subpath has been closed.
If we make this change:
var pathRedFill = CGMutablePath(rect: CGRect(origin: CGPoint(x: 10, y: 10),
size: CGSize(width: 400, height: 700)),
transform: nil)
// add this line:
pathRedFill.move(to: pathRedFill.currentPoint)
pathRedFill.addQuadCurve(to: CGPoint(x: 267, y: 121), control: CGPoint(x: 395, y: 735))
pathRedFill.closeSubpath()
var pathBlueFill = CGMutablePath(rect: CGRect(origin: CGPoint(x: 120, y: 120),
size: CGSize(width: 200, height: 200)), transform: nil)
// add this line:
pathBlueFill.move(to: pathBlueFill.currentPoint)
pathBlueFill.addQuadCurve(to: CGPoint(x: 637, y: 176), control: CGPoint(x: 343, y: 451))
pathBlueFill.closeSubpath()
here's the output:
So it seems that calling .moveTo perhaps "explicitly starts a new subpath."
And then, internally, the paths/subpaths are more... complete?
Edit
For the second part of your question...
I think paths can be much more complex than it would seem on the surface.
For your specific example:
let pathRedFill = CGPath(rect: CGRect(origin: CGPoint(x: 200, y: 300),
size: CGSize(width: 200, height: 200)),
transform: nil)
var pathBlueFill = CGMutablePath()
pathBlueFill.move(to: CGPoint(x: 302.854156, y: 369.438843))
pathBlueFill.addQuadCurve(to: CGPoint(x: 296.932526, y: 386.031342), control: CGPoint(x: 218.5, y: 376.0))
pathBlueFill.closeSubpath()
pathRedFill is a clockwise path, and pathBlueFill is a counter-clockwise path.
To see the difference, try changing the clockwise var in this code... when set to true we get a correct intersectionPath:
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext()
else { return }
var pathRedFill = CGMutablePath()
var pathBlueFill = CGMutablePath()
// 200 x 300 rect path
pathRedFill = CGMutablePath(rect: CGRect(origin: CGPoint(x: 200, y: 300),
size: CGSize(width: 200, height: 200)),
transform: nil)
// switch between true and false to see the difference
let clockwise: Bool = false
var y1: CGFloat = 369.438843
var y2: CGFloat = 386.031342
if clockwise {
let bez = UIBezierPath(cgPath: pathBlueFill)
if let p = bez.reversing().cgPath.mutableCopy() {
pathBlueFill = p
}
}
pathBlueFill = CGMutablePath()
pathBlueFill.move(to: CGPoint(x: 302.854156, y: y1))
pathBlueFill.addQuadCurve(to: CGPoint(x: 296.932526, y: y2), control: CGPoint(x: 218.5, y: 376.0))
pathBlueFill.closeSubpath()
context.setBlendMode(.normal)
context.setFillColor(red: 1, green: 0, blue: 0, alpha: 0.5)
context.addPath(pathRedFill)
context.drawPath(using: .eoFill)
context.setFillColor(red: 0, green: 0, blue: 1, alpha: 0.5)
context.addPath(pathBlueFill)
context.drawPath(using: .eoFill)
context.setLineWidth(1)
context.setStrokeColor(red: 0, green: 1, blue: 0, alpha: 1)
let intersectionPath = pathRedFill.intersection(pathBlueFill, using: .evenOdd)
context.addPath(intersectionPath)
context.drawPath(using: .stroke)
}
Edit 2
The above was meant to demonstrate that mixing clockwise and counter-clockwise subpaths can be problematic. I swapped the y1 and y2 values, but didn't take into account the controlPoint y value.
To avoid changing the geometry of the blue path, instead of swapping the y1 and y2 values, we can try reversing the path:
pathBlueFill.closeSubpath()
// reverse the blue path so it's going clockwise
let bez = UIBezierPath(cgPath: pathBlueFill)
if let p = bez.reversing().cgPath.mutableCopy() {
pathBlueFill = p
}
Now we get (I believe) the same geometry, along with the desired intersection path:
This code works when the frame's x and y are 0, but fails when using different x and y's:
class Triangle: UIView {
override func draw(_ rect: CGRect) {
let path = UIBezierPath()
let startX = self.center.x
let startY: CGFloat = 0
path.move(to: CGPoint(x: startX, y: startY))
path.addLine(to: CGPoint(x: self.bounds.width, y: self.bounds.height))
path.addLine(to: CGPoint(x: 0, y: self.bounds.height))
path.close()
UIColor.green.setStroke()
path.stroke()
}
}
import UIKit
class ViewController: UIViewController {
#IBAction func animate(_ sender: UIButton) {
let triangleView = Triangle(frame: CGRect(x: 50, y: 50, width: 30, height: 30))
triangleView.backgroundColor = .clear
self.view.addSubview(triangleView)
}
}
This works:
let triangleView = Triangle(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
When failing it looks like this:
Well that is one ugly triangle. Why does it works with x: 0 and y:0 and fails when using different floats there? How can I fix this?
replace let startX = self.center.x with let startX = self. bounds.width / 2
How can I create a triangle UIImage? Here's how I'm doing it now, but it's not producing any image at all.
extension UIImage {
static func triangle(side: CGFloat, color: UIColor)->UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: side, height: side), false, 0)
let ctx = UIGraphicsGetCurrentContext()!
ctx.saveGState()
ctx.beginPath()
ctx.move(to: CGPoint(x: side / 2, y: 0))
ctx.move(to: CGPoint(x: side, y: side))
ctx.move(to: CGPoint(x: 0, y: side))
ctx.move(to: CGPoint(x: side / 2, y: 0))
ctx.closePath()
ctx.setFillColor(color.cgColor)
ctx.restoreGState()
let img = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return img
}
}
Your path does not contain any lines, so there's no region to fill. In addition you are not drawing the path.
Try something like this:
static func triangle(side: CGFloat, color: UIColor)->UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: side, height: side), false, 0)
let ctx = UIGraphicsGetCurrentContext()!
ctx.saveGState()
ctx.beginPath()
ctx.move(to: CGPoint(x: side / 2, y: 0))
//### Add lines
ctx.addLine(to: CGPoint(x: side, y: side))
ctx.addLine(to: CGPoint(x: 0, y: side))
//ctx.addLine(to: CGPoint(x: side / 2, y: 0)) //### path is automatically closed
ctx.closePath()
ctx.setFillColor(color.cgColor)
ctx.drawPath(using: .fill) //### draw the path
ctx.restoreGState()
let img = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return img
}
You might just use UIBezierPath and not use CoreGraphics at all. Furthermore, nowadays we’d use UIGraphicsImageRenderer:
extension UIImage {
static func triangle(side: CGFloat, color: UIColor) -> UIImage {
return UIGraphicsImageRenderer(size: CGSize(width: side, height: side)).image { _ in
let path = UIBezierPath()
path.move(to: CGPoint(x: side / 2, y: 0))
path.addLine(to: CGPoint(x: side, y: side))
path.addLine(to: CGPoint(x: 0, y: side))
path.close()
color.setFill()
path.fill()
}
}
}
For UIBezierPath version that still uses UIGraphicsBeginImageContextWithOptions, see previous revision of this answer.
OOPer told you about your lack of lines, and failure to actually draw the triangle.
In addition to that, I would suggest avoiding mucking around with graphics contexts. UIBezierPath makes it cleaner and easier to draw without having to worry about contexts. Also, you don't need to save and restore contexts since you are creating a temporary context and then immediately discarding it.
Here is a complete playground that draws your triangle (and fills and strokes the image rectangle so it's easier to see - you'd remove the stroke and probably fill the shape with UIColor.clear instead.)
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
extension UIImage {
static func triangle(side: CGFloat, color: UIColor)->UIImage {
UIGraphicsBeginImageContextWithOptions(CGSize(width: side, height: side), false, 0)
//First fill the bounds with white
let rectPath = UIBezierPath(rect: CGRect(x:0, y: 0, width: side, height: side))
UIColor.white.setFill() //Use clear if you want your image to only contain the triangle.
rectPath.fill()
//Now build the triangle path
let path = UIBezierPath()
path.move(to: CGPoint(x: side / 2, y: 0))
path.addLine(to: CGPoint(x: side, y: side))
path.addLine(to: CGPoint(x: 0, y: side))
path.close() //Closing the path draws the final line
color.setFill()
path.fill()
//Stroke the outer path in gray so you can see the bounds - remove if desired
UIColor.gray.setStroke()
rectPath.stroke()
let img = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return img
}
}
let imageView = UIImageView(frame: CGRect(x:0, y: 0, width: 200, height: 200))
PlaygroundPage.current.liveView = imageView
imageView.image = UIImage.triangle(side: 200.0, color: UIColor.yellow)
I wanna draw a sloping oval with UIBezierPath. There is only a method UIBezierPath.init(ovalInRect: rect) to draw a oval without slop.What can I do to draw this? thanks
Here is an example of a rotated oval:
class MyView: UIView {
override func draw(_ rect: CGRect) {
// create oval centered at (0, 0)
let path = UIBezierPath(ovalIn: CGRect(x: -75, y: -50, width: 150, height: 100))
// rotate it 30 degrees
path.apply(CGAffineTransform(rotationAngle: 30 * .pi / 180))
// translate it to where you want it
path.apply(CGAffineTransform(translationX: self.bounds.width / 2, y: self.bounds.height / 2))
// set stroke color
UIColor.blue.setStroke()
// stroke the path
path.stroke()
}
}
let view = MyView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = .white
Here it is running in a Playground:
I'm trying to figure out how to use the UIView's convertPoint function in the swift playground. I'm not getting the results I expect and I'm not sure why.
When I Try:
import UIKit
let large = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
let small = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
let point = CGPoint(x: 200, y: 200)
large.convertPoint(point, toView: small)
I expect: {x: 100, y: 100}
I actually get: {x: 200, y: 200}
What am I missing?
change your code (small view) to
let large = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
let small = UIView(frame: CGRect(x: 20, y: 20, width: 200, height: 200))
let point = CGPoint(x: 200, y: 200)
let convertedPoint = large.convertPoint(point, toView: small)
print(convertedPoint)
prints out: (180.0, 180.0)
and that is totally correct. take a look at the image:
as you can see the red dot is at 200, 200 (exactly in the middle) of the large - dark gray - view and at 180, 180 (near the bottom right) of the small - light gray - view.
if we now get back to your example with the small view's origin at 0, 0 instead of 20, 20 the red dot is at 200, 200 (exactly in the middle) of the large view and also at 200, 200 (exactly at the bottom right) of the small view. look:
so the output you get totally makes sense! hope i could help...