I gave myself an exercise to learn Swift, based on an example I have found on the Apple Swift website:
As you can see there's a river and a few dots in it right in the middle, forming a path. So I have started looking for a similar river image on the internet and I have created a Xcode playground. This is what I have now:
So basically I have an UIView
with a subview consisting in the river image I have found and a dot made with UIBezierPath
.
My first question is: is this the right way to drawn on to a UIView? I mean using a UIBezierPath
. And my second question is: how do I draw the dot at a precise coordinate inside the UIView
? (UIBezierPath
or everything else?)
Just to be more precise, my intent here is to make an algorithm to make the program recognize the image and based on the pixel color it would draw a line with dots from the start to the end of the river, passing between it's middle.
To draw UIBezierPath
on 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 dot with radius 8 with coordinates 10,20 on your view.
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)
Here is an attempt at the lines part 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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With