2014-02-26 42 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) 
      } 
     } 
    }) 
}