检查缩放级别是否已更改 [英] Check whether zoom level changed
问题描述
我在iPhone上使用MapKit。
如何知道用户何时更改缩放级别(放大地图)?
I'm using MapKit on iPhone. How can I know when the user changes the zoom level (zoom in\out the map)?
我尝试使用 mapView :(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated; 但即使只拖动地图也会调用它。
不幸的是,当拖动地图时,mapView.region.span也会发生变化......
I've tried to use mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated; but that's called even when the map is only dragged. Unfortunately, when the map is dragged the mapView.region.span changes as well...
帮助?
10x
推荐答案
计算缩放级别非常简单。请参阅下面的代码段。您可以从 MKMapView
实例上的 visibleMapRect
属性中获取mRect参数。
It is pretty simple to calculate the zoom level. See the snippet below. You can get the mRect parameter from the visibleMapRect
property on your MKMapView
instance.
+ (NSUInteger)zoomLevelForMapRect:(MKMapRect)mRect withMapViewSizeInPixels:(CGSize)viewSizeInPixels
{
NSUInteger zoomLevel = MAXIMUM_ZOOM; // MAXIMUM_ZOOM is 20 with MapKit
MKZoomScale zoomScale = mRect.size.width / viewSizeInPixels.width; //MKZoomScale is just a CGFloat typedef
double zoomExponent = log2(zoomScale);
zoomLevel = (NSUInteger)(MAXIMUM_ZOOM - ceil(zoomExponent));
return zoomLevel;
}
您可能只是停在计算 zoomScale
因为它会告诉你缩放是否完全改变了。
You could probably just stop at the step for calculating the zoomScale
as that will tell you if the zoom has changed at all.
我想通过阅读Troy Brants优秀的博客帖子来解决这个问题主题:
I figured this stuff out from reading Troy Brants excellent blog posts on the topic:
http://troybrant.net/blog/2010/01/mkmapview-and-zoom-levels-a-visual-guide/
Swift 3
extension MKMapView {
var zoomLevel: Int {
let maxZoom: Double = 20
let zoomScale = self.visibleMapRect.size.width / Double(self.frame.size.width)
let zoomExponent = log2(zoomScale)
return Int(maxZoom - ceil(zoomExponent))
}
}
这篇关于检查缩放级别是否已更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!