iPhone Note #13: Drawing Point, Line, Polygon on top of MKMapview
Now I have a reason to study Quartz2D! I am trying to draw a point, line and polygon on top of MKMapview. I will list below important links for reference:
-
Always use Apple’s iPhone OS Reference Library Documentation.. Under “Topics” > “Graphics & Animation” you will find a lot of references, guides and sample code.
-
Start out with the Getting Started with Graphics and Animation. Note, if you ever read the line below and try to find Finger Sketch, please drop me a comment. I could not find it anywhere!
“Next, examine the Finger Sketch sample code in Xcode.”
-
Note: I haven’t read everything on Quartz 2D Programming Guide, but I went straight to the Paths Section.
-
Lets look at some sample codes, especially the QuartzDemo.
-
Now, I presume you know IB, add a MKMapView and a UIToolbar at the bottom. Add four UIBarButtonItems for: Map, Point, Line, Polygon. Set MKMapView’s delegate to the File’s Owner. Hook up the UIBarButtonItem IBOutlets to your buttons, so we can change the appearance of the buttons when pressed. Lastly, hook up our IBAction methods for each button.
The Map button allows to pan/zoom on the Map. If any of the three geometry buttons (PT, LN, PG) is pressed, we unhide the GeometryView(which is a UIView) to allow touchEvents to proceed.
TO DO: Watch out for this segment as I will update it with code later.
- Now to draw a line, we implement the code below in our GeometryView.drawRect method. As we loop through each Pin, we add a line to the point. Afterwards, we stroke the path, thus drawing the lines.
CGContextRef context = UIGraphicsGetCurrentContext(); // Drawing lines with a white stroke color CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 1.0); // Draw them with a 2.0 stroke width so they are a bit more visible. CGContextSetLineWidth(context, 2.0); if( [pinFactory actualPinCount] > 1){ Pin *pin1 = (Pin *)[[pinFactory pinArray] objectAtIndex:]; CGPoint pt1 = pin1.touchLocation; CGContextMoveToPoint(context, pt1.x, pt1.y); for (int i = 1; i < ([pinFactory actualPinCount]); i++) { Pin *pin2 = (Pin *)[[pinFactory pinArray] objectAtIndex:i]; CGPoint pt2 = pin2.touchLocation; CGContextAddLineToPoint(context, pt2.x, pt2.y); } CGContextStrokePath(context); } |
- To draw a polygon, we close the path of lines then fill the polygon.
CGContextClosePath(context); CGContextDrawPath(context, kCGPathFillStroke); |
Note: I’ll try to post the sample code when I have time. I’m trying to minimize blogging to 10 mins per post as my work tasks/personal development tasks is piling up…