iOS開發(fā)——地圖標(biāo)記物根據(jù)數(shù)據(jù)變化

在進(jìn)行地圖應(yīng)用開發(fā)的時(shí)候經(jīng)常使用圖片自定義標(biāo)記物。但是如果有這樣的需求:根據(jù)服務(wù)器返回?cái)?shù)據(jù)的時(shí)間距當(dāng)前時(shí)間的遠(yuǎn)近展示不同透明度的標(biāo)記物,該怎么辦呢?

我是這樣實(shí)現(xiàn)的。首先要實(shí)現(xiàn)自定義的annotation,應(yīng)該先創(chuàng)建一個(gè)遵守<MKAnnotation>的類,頭文件應(yīng)該是這樣的:

#import <Foundation/Foundation.h>
#import <MapKit/MapKit.h>

@interface HZYAnnotation : NSObject<MKAnnotation>
@property (nonatomic) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@end

為了實(shí)現(xiàn)我們的需求,現(xiàn)在給這個(gè)類添加一個(gè)屬性,用來記錄標(biāo)記物的透明度

@property (nonatomic, assign) CGFloat alpha;

接下來,在mapView所在的控制器中實(shí)現(xiàn)MKMapView的這個(gè)代理方法

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(HZYAnnotation *)annotation{
    static NSString *ID = @"anno";
    if ([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    MKAnnotationView *annoView = [mapView dequeueReusableAnnotationViewWithIdentifier:ID];
    if (annoView == nil) {
        annoView = [[MKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:ID];
    }
    annoView.canShowCallout = YES;
    annoView.image = [[UIImage imageNamed:@"danger_dot"] imageByApplyingAlpha:annotation.alpha];
    return annoView;
}

亮點(diǎn)就在倒數(shù)第三行,annoView的image,通過annotation的alpha屬性設(shè)置了透明度。為什么不直接設(shè)置annoView的alpha?因?yàn)檫@樣做會(huì)導(dǎo)致Callout(就是點(diǎn)擊標(biāo)記物出現(xiàn)的小標(biāo)簽)的透明度一起變化。

最后,在添加標(biāo)記物的方法中給annotation的alpha屬性賦值就可以了,例如這樣:

HZYAnnotation *annotation = [[HZYAnnotation alloc]init];
CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(anno.latitude, anno.longitude);
annotation.coordinate = coordinate;
annotation.title = anno.addr;
annotation.subtitle = [self caculateHourBefore:anno.time];
annotation.alpha = 1 - (currentDate - anno.time) / (60 * 60 * 4.0);
[self.mapView addAnnotation:annotation];

擴(kuò)展開來,通過這個(gè)思路,你可以為HZYAnnotion這個(gè)類添加任何屬性,并據(jù)此來改變標(biāo)記物的樣式。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容