如何将自定义透明MKAnnotation添加到MKMapView?

时间:2014-12-16 23:53:06

标签: ios iphone mkmapview calayer mkannotationview

所以我试图复制以下场景(半透明注释视图):

enter image description here

我尝试了以下实施失败:

1-创建具有30%不透明度的自定义图像并添加到地图--->结果:图像保持不透明。

代码:

-(id)initWithAnnotation:(id<MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier{

self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
if (self) {

    LLAnnotation *myA = (LLAnnotation*) annotation;

    self.accessibilityLabel = myA.title;
    self.annotation = myA;
    self.enabled = YES;
    self.canShowCallout = YES;

    self.centerOffset = CGPointMake(5,-10);

    self.backgroundColor = [UIColor yellowColor];

    self.image = [UIImage imageNamed:@"circle"];
}

return self;

}`

然后将其添加到 - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation _

2-将子图层添加到AnnotationView并清除它---&gt;结果:不显示任何注释。

代码:

    - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation_
{

    if (annotation_ == mapView.userLocation) return nil;

    MKAnnotationView *m = [[MKAnnotationView alloc] initWithAnnotation:annotation_ reuseIdentifier:@"default"];

//    m.backgroundColor = [UIColor clearColor];

    CALayer *layer = [[CALayer alloc]init];

    layer.frame = m.frame;

    layer.backgroundColor = [UIColor lightGreenColor].CGColor;

    [m.layer addSublayer:layer];

    m.layer.cornerRadius = m.frame.size.width/2;
    m.layer.borderWidth = 2;
    m.layer.masksToBounds = YES;

    return m;
}

我当时认为在注释之上添加MKOverlay可能是一种解决方法,但它不应该是我认为的方式。

是否有人就如何实施此建议提出其他建议?

2 个答案:

答案 0 :(得分:5)

创建UIImageView对象并使其看起来像您需要的图像。

viewForAnnotation委托方法中添加作为annotationView的子视图可以解决问题。

此外,您还需要为注释图像设置中心位置偏移,以便为注释提供完全正确的位置位置。

请看下面的代码:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation_
{

    if (annotation_ == mapView.userLocation) return nil;

    MKAnnotationView *m = [[MKAnnotationView alloc] initWithAnnotation:annotation_ reuseIdentifier:@"default"];

    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(m.center.x, m.center.y, 20, 20)];
    [imageView setBackgroundColor:[UIColor colorWithRed:0.7294 green:0.7843 blue:0.1921 alpha:1.0]];

    imageView.layer.cornerRadius = imageView.frame.size.width / 2;
    imageView.alpha = 0.6f;
    [m addSubview:imageView];

    // Also set center offset for annotation  
    [m setCenterOffset:CGPointMake(-10, -20)];

    return m;
}

enter image description here

答案 1 :(得分:0)

我要做的是在Photoshop中创建一个具有透明背景的图像,然后在顶部添加所需的黄色圆圈。然后将该圆圈的不透明度变为您想要的不透明度。将图像另存为PNG。

保存图像后,将其添加到Xcode项目中。添加后,在viewForAnnotation下添加以下行。

annotationView.image = [UIImage imageNamed:@"ThisIsThePNGImagesName.png"];

希望有所帮助:)

相关问题