2014-02-26 19 views
5

我试图找出MKMapRect的大小(即iPhone的320x568点)。将MKMapRect转换为CGRect

有没有类似的东西转换坐标点?即

[self.mapView convertCoordinate:coordinate1 toPointToView:self.view]; 

回答

6

地图视图具有convertRegion:toRectToView:方法,该方法需要一个MKCoordinateRegion并将其转换为CGRect相对于指定视图。

如果您有MKMapRect,请先使用MKCoordinateRegionForMapRect函数将其转换为MKCoordinateRegion,然后再调用convertRegion:toRectToView:

实施例:

MKCoordinateRegion mkcr = MKCoordinateRegionForMapRect(someMKMapRect); 

CGRect cgr = [mapView convertRegion:mkcr toRectToView:self.view]; 


记住的是,虽然MKMapRect一段固定的区域将不会作为地图改变被缩放或平移,相应CGRect在其originsize变化。

0

也许作为一个实际的例子...我用这个代码在屏幕上添加一个叠加到地图上,然后检查是否需要更新屏幕的哪一部分。

此方法是MKOverlay类的一部分。我的UIViewController被命名为“MyWaysViewController”,并在屏幕上的地图上被称为“MapOnScreen”(只是为了了解代码)

它的斯威夫特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) 
      } 
     } 
    }) 
}