2011-11-25 95 views
5

我使用mapkit在iPhone與iOS 4 我使用的是自定義的疊加和定製覆蓋圖,繪製在地圖上的形狀不描邊路徑。 目前,形狀只是矩形,但我正在計劃一些更復雜的東西。這就是爲什麼我不使用MKPolygon覆蓋類型。 這是我的重疊視圖繪製方法的代碼:可以mapkit重疊視圖

-(void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context 
{ 
    // Clip context to bounding rectangle 
    MKMapRect boundingMapRect = [[self overlay] boundingMapRect]; 
    CGRect boundingRect = [self rectForMapRect:boundingMapRect]; 
    CGContextAddRect(context, boundingRect); 
    CGContextClip(context); 

    // Define shape 
    CGRect shapeRect = CGRectMake(0.5f, 0.5f, boundingRect.size.width - 1.0f, boundingRect.size.height - 1.0f); 

    // Fill 
    CGContextSetRGBFillColor(context, 0.5f, 0.5f, 0.5f, 0.5f); 
    CGContextFillRect(context, shapeRect); 

    // Stroke 
    CGContextSetRGBStrokeColor(context, 0, 0, 0, 0.75f); 
    CGContextSetLineWidth(context, 1.0f); 
    CGContextStrokeRect(context, shapeRect); 
} 

的問題是,矩形得到正確填寫(所以會出現他們的邊界矩形設置正確),但他們沒有得到撫摸。 任何人都可以幫忙嗎? 謝謝!

+0

雖然我不知道解決方案,但我只是想引起您的注意[CGRectInset](http://developer.apple.com/library/ios/DOCUMENTATION/GraphicsImaging/Reference/CGGeometry/Reference/reference。 html#// apple_ref/c/func/CGRectInset)(而不是用'CGRectMake'創建矩形)。 – DarkDust

+0

剛剛發生在我身上:如果你進一步插入矩形,矩形會被撫摸嗎?所以先填充它,然後用另一個0.5插入矩形,然後撫摸它? – DarkDust

+0

找到與此相關的另一個問題:http://stackoverflow.com/questions/5274164/custom-mkoverlayview-line-width如此看來,問題是線寬縮放,它看起來像我解決我這樣的代碼:CGContextSetLineWidth(context,5.0f/zoomScale); –

回答

2

正如在以前的一些評論報道,問題是線寬。更一般地,所有的繪圖自動縮放到按照地圖縮放,所以如果你想要一些繪圖指標是變焦無關,你必須zoomScale將其分攤。

這裏是新的代碼,這在我的iPhone 4可以正常工作:

-(void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context 
{ 
    // Clip context to bounding rectangle 
    MKMapRect boundingMapRect = [[self overlay] boundingMapRect]; 
    CGRect boundingRect = [self rectForMapRect:boundingMapRect]; 
    CGContextAddRect(context, boundingRect); 
    CGContextClip(context); 

    // Define shape 
    CGRect shapeRect = CGRectInset(boundingRect, 2.0f/zoomScale, 2.0f/zoomScale); 

    // Fill 
    CGContextSetRGBFillColor(context, 0.5f, 0.5f, 0.5f, 0.5f); 
    CGContextFillRect(context, shapeRect); 

    // Stroke 
    CGContextSetRGBStrokeColor(context, 0, 0, 0, 0.75f); 
    CGContextSetLineWidth(context, 4.0f/zoomScale); 
    CGContextStrokeRect(context, shapeRect); 
} 

我還會報告我使用的疊加來計算並返回邊框的代碼,因爲我覺得它可以幫助:

-(MKMapRect)boundingMapRect 
{ 
    // Overlay bounds 
    CLLocationCoordinate2D topLeftcoordinate = <the top-left coordinate of overlay>; 
    CLLocationCoordinate2D bottomRightCoordinate = <the bottom-right coordinate of overlay>; 

    // Convert them to map points 
    MKMapPoint topLeftPoint = MKMapPointForCoordinate(topLeftcoordinate); 
    MKMapPoint bottomRightPoint = MKMapPointForCoordinate(bottomRightCoordinate); 

    // Calculate map rect 
    return MKMapRectMake(topLeftPoint.x, topLeftPoint.y, bottomRightPoint.x - topLeftPoint.x, topLeftPoint.y - bottomRightPoint.y); 
} 

謝謝大家的意見和建議。