10

我正在尝试在 MKMapView 上绘制一些包含文本的圆形叠加层。我对 MKCircleView 进行了子类化,我在其中放置了以下内容(基于this),但没有出现文本。圆圈正确显示。(也尝试了第一个响应的解决方案,结果相同)。

-(void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context {
   [super drawMapRect:mapRect zoomScale:zoomScale inContext:context];
   NSString * t= @"XXXXX\nXXXX" ;
   UIGraphicsPushContext(context);
   CGContextSaveGState(context); 
   [[UIColor redColor] set];
   CGRect overallCGRect = [self rectForMapRect:[self.overlay boundingMapRect]];
   NSLog(@"MKC :  %lf, %lf ----> %lf , %lf ", mapRect.origin.x ,mapRect.origin.y , overallCGRect.origin.x, overallCGRect.origin.y);
   [t drawInRect:overallCGRect withFont:[UIFont fontWithName:@"Arial" size:10.0] lineBreakMode:UILineBreakModeClip alignment:UITextAlignmentCenter];
   CGContextRestoreGState(context);
   UIGraphicsPopContext();
}

调试时,我得到这样的值

MKC :  43253760.000000, 104071168.000000 ----> 1.776503 , 1.999245 
MKC :  43253760.000000, 104071168.000000 ----> -1.562442 , -2.043090

他们正常吗?我错过了什么?

谢谢。

4

3 回答 3

12

我相信您的代码正在运行,问题是文本没有正确缩放使其不可见。

根据zoomScale使用MKRoadWidthAtZoomScale函数缩放字体大小:

[t drawInRect:overallCGRect withFont:[UIFont fontWithName:@"Arial" 
    size:(10.0 * MKRoadWidthAtZoomScale(zoomScale))] 
    lineBreakMode:UILineBreakModeClip alignment:UITextAlignmentCenter];

还要确保使用与底层圆圈颜色不同的文本颜色。

请注意,使用drawInRect将导致文本被限制在圆圈内并可能被截断。如果您想始终显示所有文本,则可以drawAtPoint改用。

于 2011-10-21T03:10:28.973 回答
4

结合这里的答案并为 IOS7 更新:

-(void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context
{
    [super drawMapRect:mapRect zoomScale:zoomScale inContext:context];

    UIGraphicsPushContext(context);
    CGContextSaveGState(context);
    [[UIColor blueColor] set];

    NSDictionary *fontAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:10.0f * MKRoadWidthAtZoomScale(zoomScale)]};
    CGSize size = [[[self overlay] title] sizeWithAttributes:fontAttributes];
    CGFloat height = ceilf(size.height);
    CGFloat width  = ceilf(size.width);

    CGRect circleRect = [self rectForMapRect:[self.overlay boundingMapRect]];
    CGPoint center = CGPointMake(circleRect.origin.x + circleRect.size.width /2, circleRect.origin.y + circleRect.size.height /2);
    CGPoint textstart = CGPointMake(center.x - width/2, center.y - height /2 );

    [[[self overlay] title] drawAtPoint:textstart withAttributes:fontAttributes];

    CGContextRestoreGState(context);
    UIGraphicsPopContext();
}
于 2014-09-10T14:15:10.407 回答
2

您的文本很可能被绘制到一个不可见的矩形上。

我要做的第一件事是尝试将值打印为 %f 而不是 %lf,因为这些值看起来很疯狂。您还应该为两个矩形(和)打印出.size.width和。.size.heightmapRectoverallCGRect

如果这不能引导您进行合理的矩形定义,那么请尝试自己定义一个 CGRectCGRectMake(0,0,100,20)并查看文本是否绘制。

您也可以尝试简单地绘制一个填充的矩形,与overallCGRect您将文本绘制到的相同。

于 2011-10-20T23:52:41.260 回答