[英]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.