无法在mapkit叠加视图上描边路径

问题描述 投票:5回答:2

我正在使用iOS 4的iPhone上使用mapkit。我正在使用自定义叠加层和自定义叠加层视图在地图上绘制形状。目前,形状只是矩形,但是我正在计划更复杂的东西。这就是为什么我不使用MKPolygon覆盖类型的原因。这是我的叠加视图绘制方法的代码:

-(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);
}

问题是矩形正确填充(因此似乎正确设置了矩形的边界),但矩形没有被描边。有人可以帮忙吗?谢谢!

ios
2个回答
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);
}

谢谢大家的评论和建议。


0
投票
  1. 当前,我们应该使用MKOverlayRenderer而不是MKOverlayView。
  2. 在方法-(void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context中,使用scaleFactor来配置线条或其他线条的笔划宽度属性可能会受到地图比例尺的影响内容。

请参阅MKOverlayRenderer的Apple官方网站drawMapRect:zoomScale:inContext:。>>

© www.soinside.com 2019 - 2024. All rights reserved.