【发布时间】:2021-08-28 17:09:09
【问题描述】:
我有一个应用程序,用户可以在其中向地图添加图像。这很简单。当我想添加旋转(取自当前地图标题)时,它变得更加困难。我用来创建图像的代码非常简单:
let imageAspectRatio = Double(image.size.height / image.size.width)
let mapAspectRatio = Double(visibleMapRect.size.height / visibleMapRect.size.width)
var mapRect = visibleMapRect
if mapAspectRatio > imageAspectRatio {
// Aspect ratio of map is bigger than aspect ratio of image (map is higher than the image), take away height from the rectangle
let heightChange = mapRect.size.height - mapRect.size.width * imageAspectRatio
mapRect.size.height = mapRect.size.width * imageAspectRatio
mapRect.origin.y += heightChange / 2
} else {
// Aspect ratio of map is smaller than aspect ratio of image (map is higher than the image), take away width from the rectangle
let widthChange = mapRect.size.width - mapRect.size.height / imageAspectRatio
mapRect.size.width = mapRect.size.height / imageAspectRatio
mapRect.origin.x += widthChange / 2
}
photos.append(ImageOverlay(image: image, boundingMapRect: mapRect, rotation: cameraHeading))
ImageOverlay 类继承自 MKOverlay,我可以轻松地在地图上绘制。这是该类的代码:
class ImageOverlay: NSObject, MKOverlay {
let image: UIImage
let boundingMapRect: MKMapRect
let coordinate: CLLocationCoordinate2D
let rotation: CLLocationDirection
init(image: UIImage, boundingMapRect: MKMapRect, rotation: CLLocationDirection) {
self.image = UIImage.fixedOrientation(for: image) ?? image
self.boundingMapRect = boundingMapRect
self.coordinate = CLLocationCoordinate2D(latitude: boundingMapRect.midX, longitude: boundingMapRect.midY)
self.rotation = rotation
}
}
我已经弄清楚我需要多少缩放和翻译上下文以适应地图上的正确位置(从中添加它)。我不知道如何旋转上下文以使图像呈现在正确的位置。
我发现地图旋转是以度为单位的,而旋转方法需要弧度(花费的时间比我敢承认的要长),但是当我应用旋转时图像会四处移动。
我使用以下代码来渲染叠加层:
override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) {
guard let overlay = overlay as? ImageOverlay else {
return
}
let rect = self.rect(for: overlay.boundingMapRect)
context.scaleBy(x: 1.0, y: -1.0)
context.translateBy(x: 0.0, y: -rect.size.height)
context.rotate(by: CGFloat(overlay.rotation * Double.pi / 180))
context.draw(overlay.image.cgImage!, in: rect)
}
我需要如何旋转此上下文以使图像正确对齐?
这是一个开源项目,代码为here
编辑:我尝试过(但失败了)使用某种触发函数。如果我按3 * sin(rotation) / 4 的因子进行缩放(不知道 3/4 的来源),我会得到一些旋转的正确比例,但对于其他旋转则不然。
【问题讨论】:
-
似乎您正在尝试围绕某个不是其中心的点旋转叠加层。所以这可能对你有帮助stackoverflow.com/questions/19304470/…
标签: ios mapkit cgcontext mkoverlay