将MKMapRect转换为CGRect

时间:2014-02-26 21:10:09

标签: objective-c mapkit mkmaprect

我试图找出MKMapRect的分数(即iPhone的320x568分)。

是否有类似于将坐标转换为积分的东西?即。

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

2 个答案:

答案 0 :(得分:7)

地图视图采用convertRegion:toRectToView:方法,该方法需要MKCoordinateRegion并将其转换为相对于指定视图的CGRect

如果您有MKMapRect,请先使用MKCoordinateRegion功能将其转换为MKCoordinateRegionForMapRect,然后拨打convertRegion:toRectToView:

示例:

MKCoordinateRegion mkcr = MKCoordinateRegionForMapRect(someMKMapRect);

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


请注意,虽然某些固定区域的MKMapRect不会随着地图的缩放或平移而发生变化,但相应的CGRect 会因origin和{{ 1}}。

答案 1 :(得分:0)

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

此方法是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)
            }
        }
    })
}