我需要渲染 MKPolyline
在 UIImage
不使用 MKMapView
如果可能的话(主要是出于性能原因,我想尽快显示路径,而 Map screenshotter 会异步提供 map ,就像应用程序 Strava 所做的那样)。
我想出了这段代码:
func pathImageForSize(size: CGSize) -> UIImage {
let region = regionForPath() // MKCoordinateRegion
let coordinates = locations.map { $0.coordinate }
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale)
let context = UIGraphicsGetCurrentContext()
CGContextSetStrokeColorWithColor(context, UIColor.palette_mainColor().CGColor)
CGContextSetLineWidth(context, 4.0)
CGContextBeginPath(context)
let origin = CGPoint(x: region.center.latitude - region.span.latitudeDelta / 2, y: region.center.longitude - region.span.longitudeDelta / 2)
for (index, coordinate) in coordinates.enumerate() {
let point = CGPoint(x: ((CGFloat(coordinate.latitude) - origin.x) / CGFloat(region.span.latitudeDelta)) * size.width,
y: ((CGFloat(coordinate.longitude) - origin.y) / CGFloat(region.span.longitudeDelta)) * size.height)
if index == 0 {
CGContextMoveToPoint(context, point.x, point.y)
} else {
CGContextAddLineToPoint(context, point.x, point.y)
}
}
CGContextStrokePath(context)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
该代码基本上重新调整坐标并使用 CoreGraphics 绘制它们。
路径已绘制,但它也旋转了 90 度,如您在此处看到的:
MapKit 渲染的折线:
我的代码渲染的折线:
知道我做错了什么吗?
最佳答案
我怀疑这是因为您将纬度用作“x”,将经度用作“y”。纬度是垂直维度(在顶部为北的 map 上),经度是水平维度。
关于ios - 在 UIImage 中渲染 MKPolyline,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37501535/