How to draw UIBezierPath identical to MKPolyline in a UIView - ios

Currently I am tracking my location on an MKMapView. My objective is to draw a bezier path identical to an MKPolyline created from tracked locations.
What I have attempted is: Store all location coordinates in a CLLocation array. Iterate over that array and store the lat/lng coordinates in a CLLocationCoordinate2D array. Then ensure the polyline is in the view of the screen to then convert all the location coordinates in CGPoints.
Current attempt:
#IBOutlet weak var bezierPathView: UIView!
var locations = [CLLocation]() // values from didUpdateLocation(_:)
func createBezierPath() {
bezierPathView.isHidden = false
var coordinates = [CLLocationCoordinate2D]()
for location in locations {
coordinates.append(location.coordinate)
}
let polyline = MKPolyline(coordinates: coordinates, count: coordinates.count)
fitPolylineInView(polyline: polyline)
let mapPoints = polyline.points()
var points = [CGPoint]()
for point in 0...polyline.pointCount
{
let coordinate = MKCoordinateForMapPoint(mapPoints[point])
points.append(mapView.convert(coordinate, toPointTo: polylineView))
}
print(points)
let path = UIBezierPath(points: points)
path.lineWidth = 2.0
path.lineJoinStyle = .round
let layer = CAShapeLayer(path: path, lineColor: UIColor.red, fillColor: UIColor.black)
bezierPathView.layer.addSublayer(layer)
}
extension UIBezierPath {
convenience init(points:[CGPoint])
{
self.init()
//connect every points by line.
//the first point is start point
for (index,aPoint) in points.enumerated()
{
if index == 0 {
self.move(to: aPoint)
}
else {
self.addLine(to: aPoint)
}
}
}
}
extension CAShapeLayer
{
convenience init(path:UIBezierPath, lineColor:UIColor, fillColor:UIColor)
{
self.init()
self.path = path.cgPath
self.strokeColor = lineColor.cgColor
self.fillColor = fillColor.cgColor
self.lineWidth = path.lineWidth
self.opacity = 1
self.frame = path.bounds
}
}
I am able to output the points to the console that stored from the convert(_:) method( not sure if they are correct ). Yet the there is not output on the bezierPathView-resulting in an empty-white background-view controller.

Your extensions work fine. The problem may be in the code that adds the layer to the view (which you do not show).
I'd suggest that you simplify your project, for example use predefined array of points that definitely fit to your view. For example, for a view that is 500 pixels wide and 300 pixels high, you could use something like:
let points = [
CGPoint(x: 10, y: 10),
CGPoint(x: 490, y: 10),
CGPoint(x: 490, y: 290),
CGPoint(x: 10, y: 290),
CGPoint(x: 10, y: 10)
]
Use colors that are clearly visible, like black and yellow for your stroke and fill.
Make sure that your path is correctly added to the view, for example:
let path = UIBezierPath(points: points)
let shapeLayer = CAShapeLayer(path: path, lineColor: UIColor.blue, fillColor: UIColor.lightGray)
view.layer.addSublayer(shapeLayer)
Inspect the controller that contains the view in Xcode's Interface Builder. In the debug view hierarchy function:

this might help you, in case you haven't solved it yet.
I wanted the shape of an MKPolyline as an image without any background.
I used the code above as an inspiration and had the same troubles as you had, the route was not shown.
In fact it was kind a scaling problem I think. At least it looked like that in the playground.
Anyway, with this methods I get an image of the polylines shape.
private func createPolylineShapeAsImage() -> UIImage? {
let vw = UIView(frame: mapView.bounds)
var image : UIImage?
if let polyline = viewModel.tourPolyline {
let path = createBezierPath(mapView, polyline, to: mapView)
let layer = getShapeLayer(path: path, lineColor: UIColor.white, fillColor: .clear)
vw.layer.addSublayer(layer)
image = vw.asImage()
}
return image
}
func createBezierPath(_ mapView : MKMapView, _ polyline : MKPolyline, to view : UIView) -> UIBezierPath {
let mapPoints = polyline.points()
var points = [CGPoint]()
let max = polyline.pointCount - 1
for point in 0...max {
let coordinate = mapPoints[point].coordinate
points.append(mapView.convert(coordinate, toPointTo: view))
}
let path = UIBezierPath(points: points)
path.lineWidth = 5.0
return path
}
private func getShapeLayer(path:UIBezierPath, lineColor:UIColor, fillColor:UIColor) -> CAShapeLayer {
let layer = CAShapeLayer()
layer.path = path.cgPath
layer.strokeColor = lineColor.cgColor
layer.fillColor = fillColor.cgColor
layer.lineWidth = path.lineWidth
layer.opacity = 1
layer.frame = path.bounds
return layer
}
And to get the image of the view use this extension
import UIKit
extension UIView {
// Using a function since `var image` might conflict with an existing variable
// (like on `UIImageView`)
func asImage() -> UIImage {
if #available(iOS 10.0, *) {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { rendererContext in
layer.render(in: rendererContext.cgContext)
}
} else {
UIGraphicsBeginImageContext(self.frame.size)
self.layer.render(in:UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return UIImage(cgImage: image!.cgImage!)
}
}
}

Related

CGContext Drawing two adjacent rhomboids produce a very thin gap, how to reduce it?

The two adjacent rectangle is ok as image below.
override func draw(_ rect: CGRect) {
// Drawing code
let leftTop = CGPoint(x:50,y:50)
let rightTop = CGPoint(x:150,y:100)
let leftMiddle = CGPoint(x:50,y:300)
let rightMiddle = CGPoint(x:150,y:300)
let leftDown = CGPoint(x:50,y:600)
let rightDown = CGPoint(x:150,y:650)
let context = UIGraphicsGetCurrentContext()
context?.addLines(between: [leftTop,rightTop,rightMiddle,leftMiddle])
UIColor.black.setFill()
context?.fillPath()
context?.addLines(between: [leftMiddle,rightMiddle,rightDown,leftDown])
context?.fillPath()
let leftTop1 = CGPoint(x:200,y:50)
let rightTop1 = CGPoint(x:300,y:100)
let leftMiddle1 = CGPoint(x:200,y:300)
let rightMiddle1 = CGPoint(x:300,y:350)
let leftDown1 = CGPoint(x:200,y:600)
let rightDown1 = CGPoint(x:300,y:650)
context?.addLines(between: [leftTop1,rightTop1,rightMiddle1,leftMiddle1])
UIColor.black.setFill()
context?.fillPath()
context?.addLines(between: [leftMiddle1,rightMiddle1,rightDown1,leftDown1])
context?.fillPath()
}
You may need to zoom in to see the gap. If I draw a thin line to cover the gap, then any width may overlap if the color has an alpha channel.
Change shapeColor to let shapeColor = UIColor(white: 0.0, alpha: 0.5) and add context?.setShouldAntialias(false)
I have the same result using the CGContext even if I use setShouldAntialias(true) or if I try to call strokePath() on the context. But it works fine with sublayers, CGPath and strokeColor
class RhombView: UIView {
let shapeColor: UIColor = .black
override init(frame: CGRect) {
super.init(frame: frame)
self.setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupView()
}
func setupView() {
let leftTop1 = CGPoint(x:200.0,y:50.0)
let rightTop1 = CGPoint(x:300.0,y:100.0)
let leftMiddle1 = CGPoint(x:200.0,y:300.0)
let rightMiddle1 = CGPoint(x:300.0,y:350.0)
let leftDown1 = CGPoint(x:200.0,y:600.0)
let rightDown1 = CGPoint(x:300.0,y:650.0)
var path = UIBezierPath()
path.move(to: leftTop1)
path.addLine(to: rightTop1)
path.addLine(to: rightMiddle1)
path.addLine(to: leftMiddle1)
path.close()
let subLayer1 = CAShapeLayer()
subLayer1.path = path.cgPath
subLayer1.frame = self.layer.frame
subLayer1.fillColor = shapeColor.cgColor
subLayer1.strokeColor = shapeColor.cgColor
self.layer.addSublayer(subLayer1)
path = UIBezierPath()
path.move(to: leftMiddle1)
path.addLine(to: rightMiddle1)
path.addLine(to: rightDown1)
path.addLine(to: leftDown1)
path.close()
let subLayer2 = CAShapeLayer()
subLayer2.path = path.cgPath
subLayer2.frame = self.layer.frame
subLayer2.fillColor = shapeColor.cgColor
subLayer2.strokeColor = shapeColor.cgColor
self.layer.addSublayer(subLayer2)
self.layer.backgroundColor = UIColor.white.cgColor
}
}
If you remove both subLayer.strokeColor you will see the gap.
This is related to screen resolution. On devices with high resolution one point actually has 2 or 3 pixels. That's why to draw an inclined line iOS draws some edge pixels with some opacity, when 2 lines are next to each other these edge pixels overlap. In your case I was able to fix the issue by making the following change
let leftTop1 = CGPoint(x:200,y:50)
let rightTop1 = CGPoint(x:300,y:100)
let leftMiddle1 = CGPoint(x:200,y:300)
let rightMiddle1 = CGPoint(x:300,y:350)
let leftMiddle2 = CGPoint(x:200,y:300.333)
let rightMiddle2 = CGPoint(x:300,y:350.333)
let leftDown1 = CGPoint(x:200,y:600)
let rightDown1 = CGPoint(x:300,y:650)
context?.addLines(between: [leftTop1,rightTop1,rightMiddle1,leftMiddle1])
UIColor.black.setFill()
context?.fillPath()
context?.addLines(between: [leftMiddle2,rightMiddle2,rightDown1,leftDown1])
context?.fillPath()
Basically moving down the second rhomboid by 1 pixel (1/3 = 0.333...), I have tested on a screen with 1:3 pixel density, for the solution to work on all devices you'll need to check the scaleFactor of the screen.

UICollectionView - draw a line between cells

How do I draw a line between cells in a UICollectionView that crosses over the spaces?
The intended output is something like this.:
The best that I've done is to add lines inside each cell. How do I connect the lines through the spaces?
I made an extension that you can use like this:
collectionView.drawLineFrom(indexPathA, to: indexPathB, color: UIColor.greenColor())
Here is the extension:
extension UICollectionView {
func drawLineFrom(
from: NSIndexPath,
to: NSIndexPath,
lineWidth: CGFloat = 2,
strokeColor: UIColor = UIColor.blueColor()
) {
guard
let fromPoint = cellForItemAtIndexPath(from)?.center,
let toPoint = cellForItemAtIndexPath(to)?.center
else {
return
}
let path = UIBezierPath()
path.moveToPoint(convertPoint(fromPoint, toView: self))
path.addLineToPoint(convertPoint(toPoint, toView: self))
let layer = CAShapeLayer()
layer.path = path.CGPath
layer.lineWidth = lineWidth
layer.strokeColor = strokeColor.CGColor
self.layer.addSublayer(layer)
}
}
The result looks like this:
I could achieve this with below code, might have different approach too.
Ok, so I am creating a custom UIView with custom frame and just providing the frame blindly, you can calculate based on your adjacent cells.
let cell1 = collectionView.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))
let myView = UIView.init(frame: CGRectMake((cell1?.frame.origin.x)!, ((cell1?.frame.origin.y)! + 50.0), (cell1?.frame.size.width)!*4, 10))
myView.backgroundColor = UIColor.blueColor()
collectionView.addSubview(myView)
collectionView.bringSubviewToFront(myView)
This would draw a line of height 10.0. Let me know if this helps you.
Updated #Callam's answer for Swift 5 and added a few minor modifications
Uses dequeueReusableCell instead cellForItemAtIndexPath
Uses a custom collection view cell that you'll need to create elsewhere. You'll also need to give it a reuse identifier name.
extension UICollectionView {
func drawLineFrom(
from: IndexPath,
to: IndexPath,
lineWidth: CGFloat = 2,
strokeColor: UIColor = UIColor.blue
) {
let fromPoint = self.dequeueReusableCell(withReuseIdentifier: "fooReuseIdentifier", for: from) as? FooCustomCollectionViewCell
let toPoint = self.dequeueReusableCell(withReuseIdentifier: "fooReuseIdentifier", for: to) as? FooCustomCollectionViewCell
let path = UIBezierPath()
guard let fromCenter = fromPoint?.center else { return }
guard let toCenter = toPoint?.center else { return }
path.move(to: convert(fromCenter, to: self))
path.addLine(to: convert(toCenter, to: self))
let layer = CAShapeLayer()
layer.path = path.cgPath
layer.lineWidth = lineWidth
layer.strokeColor = strokeColor.cgColor
self.layer.addSublayer(layer)
}
}

adding a border around SceneKit node

i am trying to highlight a selected node in SceneKit with a tap gesture. Unfortunately, I have not been able to accomplish it. The best thing I could do was to change the material when the node is tapped.
let material = key.geometry!.firstMaterial!
material.emission.contents = UIColor.blackColor()
Can someone suggest a way I can go about to just add a border or outline around the object instead of changing the color of the entire node?
Based on #Karl Sigiscar answer and another answer here in SO I came up with this:
func createLineNode(fromPos origin: SCNVector3, toPos destination: SCNVector3, color: UIColor) -> SCNNode {
let line = lineFrom(vector: origin, toVector: destination)
let lineNode = SCNNode(geometry: line)
let planeMaterial = SCNMaterial()
planeMaterial.diffuse.contents = color
line.materials = [planeMaterial]
return lineNode
}
func lineFrom(vector vector1: SCNVector3, toVector vector2: SCNVector3) -> SCNGeometry {
let indices: [Int32] = [0, 1]
let source = SCNGeometrySource(vertices: [vector1, vector2])
let element = SCNGeometryElement(indices: indices, primitiveType: .line)
return SCNGeometry(sources: [source], elements: [element])
}
func highlightNode(_ node: SCNNode) {
let (min, max) = node.boundingBox
let zCoord = node.position.z
let topLeft = SCNVector3Make(min.x, max.y, zCoord)
let bottomLeft = SCNVector3Make(min.x, min.y, zCoord)
let topRight = SCNVector3Make(max.x, max.y, zCoord)
let bottomRight = SCNVector3Make(max.x, min.y, zCoord)
let bottomSide = createLineNode(fromPos: bottomLeft, toPos: bottomRight, color: .yellow)
let leftSide = createLineNode(fromPos: bottomLeft, toPos: topLeft, color: .yellow)
let rightSide = createLineNode(fromPos: bottomRight, toPos: topRight, color: .yellow)
let topSide = createLineNode(fromPos: topLeft, toPos: topRight, color: .yellow)
[bottomSide, leftSide, rightSide, topSide].forEach {
$0.name = kHighlightingNode // Whatever name you want so you can unhighlight later if needed
node.addChildNode($0)
}
}
func unhighlightNode(_ node: SCNNode) {
let highlightningNodes = node.childNodes { (child, stop) -> Bool in
child.name == kHighlightingNode
}
highlightningNodes.forEach {
$0.removeFromParentNode()
}
}
SCNNode conforms to the SCNBoundingVolume Protocol.
This protocol defines the getBoundingBoxMin:max: method.
Use this to get the minimum and maximum coordinates of the bounding box of the geometry attached to the node.
Then use the SceneKit primitive type SCNGeometryPrimitiveTypeLine to draw the lines of the bounding box. Check SCNGeometryElement.
If your node is a primitive shape you can set a UIImage as the diffuse. The image will get stretched out to cover your node. If you use an image with a border on it, this will translate to creating a border on your node.
planeGeometry.firstMaterial?.diffuse.contents = UIImage(named: "blueSquareOutline.png")

UIView layer's sublayers display differently/randomly each time view appears

I have a simple custom CALayer to create an overlaying gradient effect on my UIView. Here is the code:
class GradientLayer: CALayer {
var locations: [CGFloat]?
var origin: CGPoint?
var radius: CGFloat?
var color: CGColor?
convenience init(view: UIView, locations: [CGFloat]?, origin: CGPoint?, radius: CGFloat?, color: UIColor?) {
self.init()
self.locations = locations
self.origin = origin
self.radius = radius
self.color = color?.CGColor
self.frame = view.bounds
}
override func drawInContext(ctx: CGContext) {
super.drawInContext(ctx)
guard let locations = self.locations else { return }
guard let origin = self.origin else { return }
guard let radius = self.radius else { return }
let colorSpace = CGColorGetColorSpace(color)
let colorComponents = CGColorGetComponents(color)
let gradient = CGGradientCreateWithColorComponents(colorSpace, colorComponents, locations, locations.count)
CGContextDrawRadialGradient(ctx, gradient, origin, CGFloat(0), origin, radius, [.DrawsAfterEndLocation])
}
}
I initialize and set these layers here:
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let gradient1 = GradientLayer(view: view, locations: [0.0,1.0], origin: CGPoint(x: view.frame.midX, y: view.frame.midY), radius: 100.0, color: UIColor(white: 1.0, alpha: 0.2))
let gradient2 = GradientLayer(view: view, locations: [0.0,1.0], origin: CGPoint(x: view.frame.midX-20, y: view.frame.midY+20), radius: 160.0, color: UIColor(white: 1.0, alpha: 0.2))
let gradient3 = GradientLayer(view: view, locations: [0.0,1.0], origin: CGPoint(x: view.frame.midX+30, y: view.frame.midY-30), radius: 300.0, color: UIColor(white: 1.0, alpha: 0.2))
gradient1.setNeedsDisplay()
gradient2.setNeedsDisplay()
gradient3.setNeedsDisplay()
view.layer.addSublayer(gradient1)
view.layer.addSublayer(gradient2)
view.layer.addSublayer(gradient3)
}
The view seems to display properly most of the time, but (seemingly) randomly I'll get different renderings as you'll see below. Here are some examples (the first one is what I want):
What is causing this malfunction? How do I only load the first one every time?
You have several problems.
First off, you should think of a gradient as an array of stops, where a stop has two parts: a color and a location. You must have an equal number of colors and locations, because every stop has one of each. You can see this if, for example, you check the CGGradientCreateWithColorComponents documentation regarding the components argument:
The number of items in this array should be the product of count and the number of components in the color space.
It's a product (the result of a multiplication) because you have count stops and you need a complete set of color components for each stop.
You're not providing enough color components. Your GradientLayer could have any number of locations (and you're giving it two) but has only one color. You're getting that one color's components and passing that as the components array to CGGradientCreateWithColorComponents, but the array is too short. Swift doesn't catch this error—notice that the type of your colorComponents is UnsafePointer<CGFloat>. The Unsafe part tells you that you're in dangerous territory. (You can see the type of colorComponents by option-clicking it in Xcode.)
Since you're not providing a large enough array for components, iOS is using whatever random values happen to be in memory after the components of your one color. Those may change from run to run and are often not what you want them to be.
In fact, you shouldn't even use CGGradientCreateWithColorComponents. You should use CGGradientCreateWithColors, which takes an array of CGColor so it's not only simpler to use, but safer because it's one less UnsafePointer floating around.
Here's what GradientLayer should look like:
class RadialGradientLayer: CALayer {
struct Stop {
var location: CGFloat
var color: UIColor
}
var stops: [Stop] { didSet { self.setNeedsDisplay() } }
var origin: CGPoint { didSet { self.setNeedsDisplay() } }
var radius: CGFloat { didSet { self.setNeedsDisplay() } }
init(stops: [Stop], origin: CGPoint, radius: CGFloat) {
self.stops = stops
self.origin = origin
self.radius = radius
super.init()
needsDisplayOnBoundsChange = true
}
override init(layer other: AnyObject) {
guard let other = other as? RadialGradientLayer else { fatalError() }
stops = other.stops
origin = other.origin
radius = other.radius
super.init(layer: other)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawInContext(ctx: CGContext) {
let locations = stops.map { $0.location }
let colors = stops.map { $0.color.CGColor }
locations.withUnsafeBufferPointer { pointer in
let gradient = CGGradientCreateWithColors(nil, colors, pointer.baseAddress)
CGContextDrawRadialGradient(ctx, gradient, origin, 0, origin, radius, [.DrawsAfterEndLocation])
}
}
}
Next problem. You're adding more gradient layers every time the system calls viewWillLayoutSubviews. It can call that function multiple times! For example, it will call it if your app supports interface rotation, or if a call comes in and iOS makes the status bar taller. (You can test that in the simulator by choosing Hardware > Toggle In-Call Status Bar.)
You need to create the gradient layers once, storing them in a property. If they have already been created, you need to update their frames and not create new layers:
class ViewController: UIViewController {
private var gradientLayers = [RadialGradientLayer]()
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
if gradientLayers.isEmpty {
createGradientLayers()
}
for layer in gradientLayers {
layer.frame = view.bounds
}
}
private func createGradientLayers() {
let bounds = view.bounds
let mid = CGPointMake(bounds.midX, bounds.midY)
typealias Stop = RadialGradientLayer.Stop
for (point, radius, color) in [
(mid, 100, UIColor(white:1, alpha:0.2)),
(CGPointMake(mid.x - 20, mid.y + 20), 160, UIColor(white:1, alpha:0.2)),
(CGPointMake(mid.x + 30, mid.y - 30), 300, UIColor(white:1, alpha:0.2))
] as [(CGPoint, CGFloat, UIColor)] {
let stops: [RadialGradientLayer.Stop] = [
Stop(location: 0, color: color),
Stop(location: 1, color: color.colorWithAlphaComponent(0))]
let layer = RadialGradientLayer(stops: stops, origin: point, radius: radius)
view.layer.addSublayer(layer)
gradientLayers.append(layer)
}
}
}
Your problem is the code you have written in viewWillLayoutSubviews function its is called multiple times when views loads just add a check to run it once or better yet add a check in viewdidlayoutsubviews to run it once

How to pass arguments from one class into a UIView class? Swift

I have a UIView class in my app which plots a line graph. In there, I assign my graphPoints variables like so :
var graphPoints:[Int] = [1,2,3,5,7,9]
var graphPoints2:[Int] = [1,2,3,5,7,9]
What I want to do is pass an array of Int from another class and assign those variables, but I am not sure how to do it. Initially i put all my code into one func with array [Int] as parameters and called it from another class but it stopped plotting the graph altogether. How do i do this?
Here is my UIVIew GraphPlotter class code :
import UIKit
#IBDesignable class GraphPlotter: UIView {
var graphPoints:[Int] = [1,2,3,5,7,9]
var graphPoints2:[Int] = [1,2,3,5,7,9]
//1 - the properties for the gradient
var startColor: UIColor = UIColor.redColor()
var endColor: UIColor = UIColor.greenColor()
override func drawRect(rect: CGRect) {
let width = rect.width
let height = rect.height
//set up background clipping area
let path = UIBezierPath(roundedRect: rect,
byRoundingCorners: UIRectCorner.AllCorners,
cornerRadii: CGSize(width: 8.0, height: 8.0))
path.addClip()
//2 - get the current context
let context = UIGraphicsGetCurrentContext()
let colors = [startColor.CGColor, endColor.CGColor]
//3 - set up the color space
let colorSpace = CGColorSpaceCreateDeviceRGB()
//4 - set up the color stops
let colorLocations:[CGFloat] = [0.0, 1.0]
//5 - create the gradient
let gradient = CGGradientCreateWithColors(colorSpace,
colors,
colorLocations)
//6 - draw the gradient
var startPoint = CGPoint.zero
var endPoint = CGPoint(x:0, y:self.bounds.height)
CGContextDrawLinearGradient(context,
gradient,
startPoint,
endPoint,
[])
//calculate the x point
let margin:CGFloat = 40.0
let columnXPoint = { (column:Int) -> CGFloat in
//Calculate gap between points
let spacer = (width - margin*2 - 4) /
CGFloat((self.graphPoints.count - 1))
var x:CGFloat = CGFloat(column) * spacer
x += margin + 2
return x
}
// calculate the y point
let topBorder:CGFloat = 60
let bottomBorder:CGFloat = 50
let graphHeight = height - topBorder - bottomBorder
let maxValue = graphPoints2.maxElement()!
let columnYPoint = { (graphPoint2:Int) -> CGFloat in
var y:CGFloat = CGFloat(graphPoint2) /
CGFloat(maxValue) * graphHeight
y = graphHeight + topBorder - y // Flip the graph
return y
}
// draw the line graph
UIColor.flatTealColor().setFill()
UIColor.flatTealColor().setStroke()
//set up the points line
let graphPath = UIBezierPath()
//go to start of line
graphPath.moveToPoint(CGPoint(x:columnXPoint(0),
y:columnYPoint(graphPoints2[0])))
//add points for each item in the graphPoints array
//at the correct (x, y) for the point
for i in 1..<graphPoints.count {
let nextPoint = CGPoint(x:columnXPoint(i),
y:columnYPoint(graphPoints2[i]))
graphPath.addLineToPoint(nextPoint)
}
//Create the clipping path for the graph gradient
//1 - save the state of the context (commented out for now)
CGContextSaveGState(context)
//2 - make a copy of the path
let clippingPath = graphPath.copy() as! UIBezierPath
//3 - add lines to the copied path to complete the clip area
clippingPath.addLineToPoint(CGPoint(
x: columnXPoint(graphPoints.count - 1),
y:height))
clippingPath.addLineToPoint(CGPoint(
x:columnXPoint(0),
y:height))
clippingPath.closePath()
//4 - add the clipping path to the context
clippingPath.addClip()
let highestYPoint = columnYPoint(maxValue)
startPoint = CGPoint(x:margin, y: highestYPoint)
endPoint = CGPoint(x:margin, y:self.bounds.height)
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, [])
CGContextRestoreGState(context)
//draw the line on top of the clipped gradient
graphPath.lineWidth = 2.0
graphPath.stroke()
//Draw the circles on top of graph stroke
for i in 0..<graphPoints.count {
var point = CGPoint(x:columnXPoint(i), y:columnYPoint(graphPoints2[i]))
point.x -= 5.0/2
point.y -= 5.0/2
let circle = UIBezierPath(ovalInRect:
CGRect(origin: point,
size: CGSize(width: 5.0, height: 5.0)))
circle.fill()
let label = UILabel(frame: CGRectMake(0, 0, 200, 21))
label.center = CGPointMake(160, 284)
label.textAlignment = NSTextAlignment.Center
// label.text = "I'am a test label"
self.addSubview(label)
}
//Draw horizontal graph lines on the top of everything
let linePath = UIBezierPath()
//top line
linePath.moveToPoint(CGPoint(x:margin, y: topBorder))
linePath.addLineToPoint(CGPoint(x: width - margin,
y:topBorder))
//center line
linePath.moveToPoint(CGPoint(x:margin,
y: graphHeight/2 + topBorder))
linePath.addLineToPoint(CGPoint(x:width - margin,
y:graphHeight/2 + topBorder))
//bottom line
linePath.moveToPoint(CGPoint(x:margin,
y:height - bottomBorder))
linePath.addLineToPoint(CGPoint(x:width - margin,
y:height - bottomBorder))
let color = UIColor.flatTealColor()
color.setStroke()
linePath.lineWidth = 1.0
linePath.stroke()
}
}
DBController, func dosmth where I pass the array :
func dosmth(metadata: DBMetadata!) {
let documentsDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let localFilePath = (documentsDirectoryPath as NSString).stringByAppendingPathComponent(metadata.filename)
var newarray = [Int]()
do{
let data = try String(contentsOfFile: localFilePath as String,
encoding: NSASCIIStringEncoding)
print(data)
newarray = data.characters.split(){$0 == ","}.map{
Int(String.init($0).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()))!}
print(newarray)
}
catch let error { print(error) }
//Probably wrong
GraphPlotter().graphPoints = newarray
GraphPlotter().graphPoints2 = newarray
}
So your drawRect method is based on the two variables graphPoints and graphPoints2. Create a method whose job is to update the arrays of these two variables, and then invoke setNeedsDisplay - which will go on to redraw the view.
func plotGraphPoints(gpArray1 : [Int], andMorePoints gpArray2: [Int] ) {
print("Old Values", self.graphPoints)
self.graphPoints = gpArray1
self.graphPoints2 = gpArray2
print("New values", self.graphPoints)
self.setNeedsDisplay()
}
First, I'd set these up so that any update will redraw the view:
var graphPoints:[Int]? { didSet { setNeedsDisplay() } }
var graphPoints2:[Int]? { didSet { setNeedsDisplay() } }
Note, I made those optionals, because you generally want it to handle the absence of data with nil values rather than dummy values. This does assume, though, that you'll tweak your implementation to detect and handle these nil values, e.g., before you start drawing the lines, do a
guard graphPoints != nil && graphPoints2 != nil else { return }
But, I notice that this whole class is IBDesignable, in which case, you probably want a prepareForInterfaceBuilder that provides sample data:
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
graphPoints = [1,2,3,5,7,9]
graphPoints2 = [1,2,3,5,7,9]
}
Second, your other class needs to have a reference to this custom view.
If this "other" class is the view controller and you added the custom view via IB, you would just add a #IBOutlet for the custom view to this view controller. If you added this custom view programmatically, you'd just keep a reference to it in some property after adding it to the view hierarchy. But, however you added a reference to that view, say graphView, you'd just set these properties:
graphView.graphPoints = ...
graphView.graphPoints2 = ...
If this "other" class is something other than a view controller (and in discussion, it sounds like the class in question is a controller for processing of asynchronous DropBox API), you also need to give that class some mechanism to reference the view controller (and thus the custom view). You can accomplish this by either implementing a "completion handler pattern" or a "delegate-protocol" pattern.

Resources