Конвертировать MKMapRect в CGRect
Я пытаюсь узнать размер MKMapRect в пунктах (то есть 320x568 пунктов для iPhone).
Есть ли что-то похожее на преобразование координат в точки? т.е.
[self.mapView convertCoordinate:coordinate1 toPointToView:self.view];
2 ответа
Вид карты имеет convertRegion:toRectToView:
метод, который принимает MKCoordinateRegion
и преобразует его в CGRect
относительно указанного вида.
Если у вас есть MKMapRect
, сначала преобразовать его в MKCoordinateRegion
с использованием MKCoordinateRegionForMapRect
функция, а затем вызвать convertRegion:toRectToView:
,
Пример:
MKCoordinateRegion mkcr = MKCoordinateRegionForMapRect(someMKMapRect);
CGRect cgr = [mapView convertRegion:mkcr toRectToView:self.view];
Помните, что хотя MKMapRect
для некоторой фиксированной области не изменится, так как карта масштабируется или панорамируется, соответствующая CGRect
будет варьироваться в своем origin
а также size
,
Может быть, в качестве практического примера... Я использовал этот код, чтобы добавить наложение на карту на экране, а затем проверяет, нужно ли и какую часть экрана обновлять.
Этот метод является частью класса MKOverlay. Мой UIViewController называется "MyWaysViewController", а карта на экране называется "MapOnScreen" (просто для понимания кода)
Это код Swift 3 / IOS 10
/**
-----------------------------------------------------------------------------------------------
adds the overlay to the map and sets "setNeedsDisplay()" for the visible part of the overlay
-----------------------------------------------------------------------------------------------
- Parameters:
- Returns: nothing
*/
func switchOverlayON() {
DispatchQueue.main.async(execute: {
// add the new overlay
// if the ViewController is already initialised
if MyWaysViewController != nil {
// add the overlay
MyWaysViewController!.MapOnScreen.add(self)
// as we are good citizens on that device, we check if and for what region we setNeedsDisplay()
// get the intersection of the overlay and the visible region of the map
let visibleRectOfOverlayMK = MKMapRectIntersection(
self.boundingMapRect,
MyWaysViewController!.MapOnScreen.visibleMapRect
)
// check if it is null (no intersection -> not visible at the moment)
if MKMapRectIsNull(visibleRectOfOverlayMK) == false {
// It is not null, so at least parts are visible, now a two steps aproach to
// convert MKMapRect to cgRect. first step: get a coordinate region
let visibleRectCoordinateRegion = MKCoordinateRegionForMapRect(visibleRectOfOverlayMK)
// second step, convert the region to a cgRect
let visibleRectOfOverlayCG = MyWaysViewController!.MapOnScreen.convertRegion(visibleRectCoordinateRegion, toRectTo: MyWaysViewController!.MapOnScreen)
// ask to refresh that cgRect
MyWaysViewController!.MapOnScreen.setNeedsDisplay(visibleRectOfOverlayCG)
}
}
})
}