Drawing dots and lines on a UIView

I gave myself an exercise to learn Swift, based on an example I found on the Apple Swift website :

enter image description here

As you can see there is a river and several points in it right in the middle, forming a path. So I started looking for a similar image of rivers on the Internet, and I created an Xcode playground. This is what I have now:

enter image description here

So basically I have a UIView with a subview consisting of the river image I found and the points with UIBezierPath .

My first question is: is this the right way to draw on a UIView? I mean using UIBezierPath . And my second question: how to draw a point with the exact coordinate inside the UIView ? ( UIBezierPath or everything else?)

To be more precise, I would like to make an algorithm so that the program recognizes the image and draws a line based on the color of the pixel with dots from the beginning to the end of the river, passing the middle between them.

+8
source share
2 answers

To draw a UIBezierPath in a UIView do this:

 let xCoord = 10 let yCoord = 20 let radius = 8 let dotPath = UIBezierPath(ovalInRect: CGRectMake(xCoord, yCoord, radius, radius)) let layer = CAShapeLayer() layer.path = dotPath.CGPath layer.strokeColor = UIColor.blueColor().CGColor drawingView.layer.addSublayer(layer) 

This code will draw a point with a radius of 8 with coordinates 10.20.

Update: Swift 4+

 let xCoord = 10 let yCoord = 20 let radius = 8 let dotPath = UIBezierPath(ovalIn: CGRect(x: xCoord, y: yCoord, width: radius, height: radius)) let layer = CAShapeLayer() layer.path = dotPath.cgPath layer.strokeColor = UIColor.blue.cgColor drawingView.layer.addSublayer(layer) 
+10
source

Here is an attempt to line parts of the equation:

  var offset:CGFloat = 0; var squareWidth:Int = 20 var squareRows:Int = Int(view.frame.size.width/CGFloat(squareWidth)) var squareColumns:Int = Int(view.frame.size.height/CGFloat(squareWidth)) for (index,element) in (0...squareRows).enumerate(){ for (column,element) in (0...squareColumns).enumerate(){ // Build The Square let rectanglePath = UIBezierPath(roundedRect: CGRectMake( view.frame.minX + CGFloat(squareWidth * index) - offset, view.frame.minY + CGFloat(column * squareWidth), 20, 20 ), cornerRadius: 0.00) // Style Square let a = CAShapeLayer() a.path = rectanglePath.CGPath a.strokeColor = UIColor.whiteColor().CGColor a.fillColor = nil a.opacity = 0.3 a.lineWidth = 1.5 view.layer.insertSublayer(a, atIndex: 1) } } 

View represented by layers

+2
source

Source: https://habr.com/ru/post/1237857/


All Articles