Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save karstenBriksoft/02c8aab4a917446f94b42031a95ce3ab to your computer and use it in GitHub Desktop.
Save karstenBriksoft/02c8aab4a917446f94b42031a95ce3ab to your computer and use it in GitHub Desktop.
drawing CLLocations in a CGContext
NSUInteger pointCount = self.waypoints.count;
MKMapPoint* points = calloc(sizeof(MKMapPoint), pointCount);
CGFloat minX = CGFLOAT_MAX, minY = CGFLOAT_MAX;
CGFloat maxX = 0, maxY = 0;
{
NSInteger i = 0;
for (CLLocation* location in self.waypoints)
{
MKMapPoint point = MKMapPointForCoordinate(location.coordinate);
points[i] = point;
i++;
minX = MIN(point.x, minX);
minY = MIN(point.y, minY);
maxX = MAX(point.x, maxX);
maxY = MAX(point.y, maxY);
}
}
CGFloat deltaX = maxX - minX;
CGFloat deltaY = maxY - minY;
CGFloat r = MAX(deltaX,deltaY);
UIImage* image = nil;
CGFloat inset = round(size.width / 10);
CGFloat imageExtent = size.width * [UIScreen mainScreen].scale;
CGFloat nettoExtent = imageExtent - inset - inset;
// xShift & yShift ensure that the scaled image is rendered centered
CGFloat xShift = (nettoExtent - (deltaX / r * nettoExtent)) * 0.5;
CGFloat yShift = (nettoExtent - (deltaY / r * nettoExtent)) * 0.5;
UIGraphicsBeginImageContext(CGSizeMake(imageExtent, imageExtent));
{
if (pointCount > 3)
{
CGContextRef context = UIGraphicsGetCurrentContext();
NSInteger i = 0;
for (i = 0; i <= pointCount; i++)
{
MKMapPoint mkPoint = points[i % pointCount]; // going till <= pointCount to have the first point count twice, closing the path
// add the inset and the shift to have a little padding and a centered drawing
CGPoint cgPoint = CGPointMake(inset + xShift + ((mkPoint.x - minX) / r * nettoExtent),
inset + yShift + ((mkPoint.y - minY) / r * nettoExtent));
if (i == 0)
{
CGContextMoveToPoint(context, cgPoint.x, cgPoint.y);
}
else
{
CGContextAddLineToPoint(context, cgPoint.x, cgPoint.y);
}
}
CGContextSetLineWidth(context, 2);
[[UIColor blackColor] setStroke];
CGContextStrokePath(context);
}
image = UIGraphicsGetImageFromCurrentImageContext();
}
UIGraphicsEndImageContext();
free(points);
return image;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment