[英]How to add custom transparent MKAnnotation to MKMapView?
所以我正在尝试复制以下场景(半透明注释视图):
并且我尝试了以下实现未成功:
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并清除它--->结果:不显示任何注释。
码:
- (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;
}
我当时在想,在注释的顶部添加MKOverlays可能是一种解决方法,但我认为这不是走的路。
有人对如何实现此建议有其他建议吗?
创建UIImageView
对象,并使它看起来像所需的图像。
在viewForAnnotation
委托方法中添加为注解视图的子视图即可解决问题。
另外,您需要为注释图像设置中心位置偏移,以完全正确地注释位置。
看下面的代码:
- (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;
}
我要做的是在photoshop中创建具有透明背景的图像,然后在顶部添加所需的黄色圆圈。 然后,使该圆的不透明度变为所需的不透明度。 将图像另存为PNG。
保存图像后,将其添加到Xcode项目中。 添加之后,在viewForAnnotation
下添加以下行。
annotationView.image = [UIImage imageNamed:@"ThisIsThePNGImagesName.png"];
希望有帮助:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.