iOS 7 では、MapKit フレームワークを使用してマップの静的スナップショットを作成できます。場所などを記載したメールを送信したい場合に非常に便利です。唯一欠けているのは、そのスナップショットに MKPolyline を描画するにはどうすればよいですか?
1193 次
2 に答える
9
こうやって:
- (UIImage *)drawRoute:(MKPolyline *)polyline onSnapshot:(MKMapSnapshot *)snapShot withColor:(UIColor *)lineColor {
UIGraphicsBeginImageContext(snapShot.image.size);
CGRect rectForImage = CGRectMake(0, 0, snapShot.image.size.width, snapShot.image.size.height);
// Draw map
[snapShot.image drawInRect:rectForImage];
// Get points in the snapshot from the snapshot
int lastPointIndex;
int firstPointIndex = 0;
BOOL isfirstPoint = NO;
NSMutableArray *pointsToDraw = [NSMutableArray array];
for (int i = 0; i < polyline.pointCount; i++){
MKMapPoint point = polyline.points[i];
CLLocationCoordinate2D pointCoord = MKCoordinateForMapPoint(point);
CGPoint pointInSnapshot = [snapShot pointForCoordinate:pointCoord];
if (CGRectContainsPoint(rectForImage, pointInSnapshot)) {
[pointsToDraw addObject:[NSValue valueWithCGPoint:pointInSnapshot]];
lastPointIndex = i;
if (i == 0)
firstPointIndex = YES;
if (!isfirstPoint) {
isfirstPoint = YES;
firstPointIndex = i;
}
}
}
// Adding the first point on the outside too so we have a nice path
if (lastPointIndex+1 <= polyline.pointCount {
MKMapPoint point = polyline.points[lastPointIndex+1];
CLLocationCoordinate2D pointCoord = MKCoordinateForMapPoint(point);
CGPoint pointInSnapshot = [snapShot pointForCoordinate:pointCoord];
[pointsToDraw addObject:[NSValue valueWithCGPoint:pointInSnapshot]];
}
// Adding the point before the first point in the map as well (if needed) to have nice path
if (firstPointIndex != 0) {
MKMapPoint point = polyline.points[firstPointIndex-1];
CLLocationCoordinate2D pointCoord = MKCoordinateForMapPoint(point);
CGPoint pointInSnapshot = [snapShot pointForCoordinate:pointCoord];
[pointsToDraw insertObject:[NSValue valueWithCGPoint:pointInSnapshot] atIndex:0];
}
// Draw that points
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 3.0);
for (NSValue *point in pointsToDraw){
CGPoint pointToDraw = [point CGPointValue];
if ([pointsToDraw indexOfObject:point] == 0){
CGContextMoveToPoint(context, pointToDraw.x, pointToDraw.y);
} else {
CGContextAddLineToPoint(context, pointToDraw.x, pointToDraw.y);
}
}
CGContextSetStrokeColorWithColor(context, [lineColor CGColor]);
CGContextStrokePath(context);
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resultingImage;
}
これはおそらく最善の方法ではないことを知っているので、より良い方法またはより速い方法があれば: 共有してください:)
于 2013-10-17T13:09:58.170 に答える