您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

百度地圖 iOS 自訂大頭針與氣泡樣式的完整實作

編輯:iOS 開發綜合

一、自訂大頭針與氣泡

// 根據anntation生成對應的View
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation {
    NSString *AnnotationViewID = [NSString stringWithFormat:@"renameMark%d",i];
    newAnnotation = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
    // 設置顏色
    ((BMKPinAnnotationView*)newAnnotation).pinColor = BMKPinAnnotationColorPurple;
    // 從天上掉下效果
    ((BMKPinAnnotationView*)newAnnotation).animatesDrop = YES;
    // 設置可拖拽
    ((BMKPinAnnotationView*)newAnnotation).draggable = YES;
    //設置大頭針圖標
    ((BMKPinAnnotationView*)newAnnotation).image = [UIImage imageNamed:@"zhaohuoche"];
    UIView *popView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 60)];
    //設置彈出氣泡圖片
    UIImageView *image = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"wenzi"]];
    image.frame = CGRectMake(0, 0, 100, 60);
    [popView addSubview:image];
    //自定義顯示的內容
    UILabel *driverName = [[UILabel alloc]initWithFrame:CGRectMake(0, 3, 100, 20)];
    driverName.text = @"張XX師傅";
    driverName.backgroundColor = [UIColor clearColor];
    driverName.font = [UIFont systemFontOfSize:14];
    driverName.textColor = [UIColor whiteColor];
    driverName.textAlignment = NSTextAlignmentCenter;
    [popView addSubview:driverName];
    UILabel *carName = [[UILabel alloc]initWithFrame:CGRectMake(0, 25, 100, 20)];
    carName.text = @"京A123456";
    carName.backgroundColor = [UIColor clearColor];
    carName.font = [UIFont systemFontOfSize:14];
    carName.textColor = [UIColor whiteColor];
    carName.textAlignment = NSTextAlignmentCenter;
    [popView addSubview:carName];
    BMKActionPaopaoView *pView = [[BMKActionPaopaoView alloc]initWithCustomView:popView];
    pView.frame = CGRectMake(0, 0, 100, 60);
    ((BMKPinAnnotationView*)newAnnotation).paopaoView = nil;
    ((BMKPinAnnotationView*)newAnnotation).paopaoView = pView;
    i++;
    return newAnnotation;
}

二、最直白的氣泡自訂方式

 

做法很樸素:自己排一個 UIView 當內容,再包成 BMKActionPaopaoView。

//改變標注圖片和自定義氣泡
-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation {
    BMKAnnotationView *annotationView=[[BMKAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
    annotationView.image =[UIImage imageNamed:@"bike.gif"];
    //自定義內容氣泡
    UIView *areaPaoView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 100)];
    areaPaoView.layer.cornerRadius=8;
    areaPaoView.layer.masksToBounds=YES;
    areaPaoView.layer.contents =(id)[UIImage imageNamed:@"pao.png"].CGImage;//這張圖片是做好的透明
    if ([annotation.title isEqualToString:@"1"]) {
        UILabel *labelNo = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, 200, 30)];
        labelNo.text =[NSString stringWithFormat:@"站點編號:%@",@"1"];
        labelNo.textColor = [UIColor blackColor];
        labelNo.backgroundColor = [UIColor clearColor];
        [areaPaoView addSubview:labelNo];
        UILabel *labelStationName = [[UILabel alloc]initWithFrame:CGRectMake(10, 20, 200, 30)];
        labelStationName.text =[NSString stringWithFormat:@"站點名稱:昆山中學"];
        labelStationName.textColor = [UIColor blackColor];
        labelStationName.backgroundColor = [UIColor clearColor];
        [areaPaoView addSubview:labelStationName];
        UILabel *labelSumNum = [[UILabel alloc]initWithFrame:CGRectMake(10, 40, 200, 30)];
        labelSumNum.text =[NSString stringWithFormat:@"總樁數:30"];
        labelSumNum.textColor = [UIColor blackColor];
        labelSumNum.backgroundColor = [UIColor clearColor];
        [areaPaoView addSubview:labelSumNum];
        UILabel *labelBicycleNum = [[UILabel alloc]initWithFrame:CGRectMake(10, 60, 200, 30)];
        labelBicycleNum.text =[NSString stringWithFormat:@"可借車:20"];
        labelBicycleNum.textColor = [UIColor blackColor];
        labelBicycleNum.backgroundColor = [UIColor clearColor];
        [areaPaoView addSubview:labelBicycleNum];
    }
    BMKActionPaopaoView *paopao=[[BMKActionPaopaoView alloc]initWithCustomView:areaPaoView];
    annotationView.paopaoView=paopao;
    return annotationView;
}

三、批量添加標註與氣泡

1. 一次加入多個標註

[_mapView addAnnotations:array];

array 中放的是 BMKPointAnnotation 物件陣列。加入後會觸發下面的代理方法:

#pragma mark -- BMKMapdelegate
/**
 *根據anntation生成對應的View
 *@param mapView 地圖View
 *@param annotation 指定的標注
 *@return 生成的標注View
 */
-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation {
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        BMKPinAnnotationView *newAnnotationView = [[BMKPinAnnotationView alloc]initWithAnnotation:annotation reuseIdentifier:@"myAnnotation"];
        newAnnotationView.animatesDrop = YES;
        newAnnotationView.annotation = annotation;
        //這裡我根據自己需要,繼承了BMKPointAnnotation,添加了標注的類型等信息
        MyBMKPointAnnotation *tt = (MyBMKPointAnnotation *)annotation;
        //判斷類別,需要添加不同類別,來賦予不同的標注圖片
        if (tt.profNumber == 100000) {
            newAnnotationView.image = [UIImage imageNamed:@"ic_map_mode_category_merchants_normal.png"];
        }else if (tt.profNumber == 100001){ }
        //設定popView的高度,根據是否含有縮略圖
        double popViewH = 60;
        if (annotation.subtitle == nil) {
            popViewH = 38;
        }
        UIView *popView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth-100, popViewH)];
        popView.backgroundColor = [UIColor whiteColor];
        [popView.layer setMasksToBounds:YES];
        [popView.layer setCornerRadius:3.0];
        popView.alpha = 0.9;
        //自定義氣泡的內容,添加子控件在popView上
        UILabel *driverName = [[UILabel alloc]initWithFrame:CGRectMake(8, 4, 160, 30)];
        driverName.text = annotation.title;
        driverName.numberOfLines = 0;
        driverName.backgroundColor = [UIColor clearColor];
        driverName.font = [UIFont systemFontOfSize:15];
        driverName.textColor = [UIColor blackColor];
        driverName.textAlignment = NSTextAlignmentLeft;
        [popView addSubview:driverName];
        UILabel *carName = [[UILabel alloc]initWithFrame:CGRectMake(8, 30, 180, 30)];
        carName.text = annotation.subtitle;
        carName.backgroundColor = [UIColor clearColor];
        carName.font = [UIFont systemFontOfSize:11];
        carName.textColor = [UIColor lightGrayColor];
        carName.textAlignment = NSTextAlignmentLeft;
        [popView addSubview:carName];
        if (annotation.subtitle != nil) {
            UIButton *searchBn = [[UIButton alloc]initWithFrame:CGRectMake(170, 0, 50, 60)];
            [searchBn setTitle:@"查看路線" forState:UIControlStateNormal];
            searchBn.backgroundColor = mainColor;
            searchBn.titleLabel.numberOfLines = 0;
            [searchBn addTarget:self action:@selector(searchLine)];
            [popView addSubview:searchBn];
        }
        BMKActionPaopaoView *pView = [[BMKActionPaopaoView alloc]initWithCustomView:popView];
        pView.frame = CGRectMake(0, 0, ScreenWidth-100, popViewH);
        ((BMKPinAnnotationView*)newAnnotationView).paopaoView = nil;
        ((BMKPinAnnotationView*)newAnnotationView).paopaoView = pView;
        return newAnnotationView;
    }
    return nil;
}

點擊標註與氣泡時的回應:

/**
 * 當選中一個annotation views時,調用此接口
 */
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view {
    _shopCoor = view.annotation.coordinate;
}
/**
 * 選中氣泡調用方法
 */
- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view {
    MyBMKPointAnnotation *tt = (MyBMKPointAnnotation *)view.annotation;
    if (tt.shopID) {
        BusinessIfonUVC *BusinessIfonVC = [[BusinessIfonUVC alloc]init];
        BusinessIfonVC.shopId = tt.shopID;
        [self.navigationController pushViewController:BusinessIfonVC animated:YES];
    }
}

2. 路線規劃與逆地理編碼

用座標反查地址:

-(void)getStartAddress {
    //起點地址
    CLGeocoder *Geocoder = [[CLGeocoder alloc]init];
    CLGeocodeCompletionHandler handler = ^(NSArray *place,NSError *error){
        for(CLPlacemark *placemark in place){
            NSString *tmp = [[NSString alloc]init];
            tmp = placemark.subThoroughfare;
            if (tmp == nil) {
                tmp = @"";
            }
            NSString *startAdr = [[NSString alloc]initWithFormat:@"%@%@",placemark.thoroughfare,tmp];
            _startCityText.text = placemark.locality;
            if ([startAdr isEqualToString:@"(null)"]) {
                _startAddrText.text = @"獲取地址失敗";
            }else{
                _startAddrText.text = startAdr;
            }
        }
    };
    CLLocation *loc = [[CLLocation alloc]initWithLatitude:self.startCoor.latitude longitude:self.startCoor.longitude];
    [Geocoder reverseGeocodeLocation:loc completionHandler:handler];
}

公交路線檢索,這裡把乘車與換乘資訊整理進 LineInfo、steps 等模型:

- (void)onGetTransitRouteResult:(BMKRouteSearch*)searcher result:(BMKTransitRouteResult*)result errorCode:(BMKSearchErrorCode)error {
    NSMutableArray *lineArr = [[NSMutableArray alloc]init];
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        for(int j = 0; j < [result.routes count];j++) {
            NSMutableArray *busTitleArr = [[NSMutableArray alloc]init];
            NSMutableArray *lineStepsArr = [[NSMutableArray alloc]init];
            NSMutableArray *stepsArr = [[NSMutableArray alloc]init];
            //生成數據模型
            LineInfoModel *lineInfo = [[LineInfoModel alloc]init];
            BMKTransitRouteLine* plan = (BMKTransitRouteLine*)[result.routes objectAtIndex:j];
            //數據模型:獲得路線長度
            lineInfo.distance = plan.distance;
            //數據模型:獲得路線消耗時間
            lineInfo.dates = plan.duration.dates;
            lineInfo.hours = plan.duration.hours;
            lineInfo.minutes = plan.duration.minutes;
            lineInfo.seconds = plan.duration.seconds;
            // 獲得軌跡點
            lineInfo.planStepsArr = plan.steps;
            // 計算路線方案中的路段數目
            int size = [plan.steps count];
            int planPointCounts = 0;
            for (int i = 0; i < size; i++) {
                BMKTransitStep* transitStep = [plan.steps objectAtIndex:i];
                //數據模型:獲得乘坐公交數組
                if (transitStep.vehicleInfo.title) {
                    [busTitleArr addObject:transitStep.vehicleInfo.title];
                }
                //數據模型:獲取換乘信息
                if (transitStep.instruction) {
                    transitStep.instruction = [transitStep.instruction stringByReplacingOccurrencesOfString:@"<font color=\"#313233\">" withString:@""];
                    [lineStepsArr addObject:transitStep.instruction];
                }
                if(i==0){
                    RouteAnnotation* item = [[RouteAnnotation alloc]init];
                    item.coordinate = plan.starting.location;
                    item.title = @"起點";
                    item.type = 0;
                }else if(i==size-1){
                    RouteAnnotation* item = [[RouteAnnotation alloc]init];
                    item.coordinate = plan.terminal.location;
                    item.title = @"終點";
                    item.type = 1;
                    [stepsArr addObject:item];
                }
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = transitStep.entrace.location;
                item.title = transitStep.instruction;
                item.type = 3;
                [stepsArr addObject:item];
                //軌跡點總數累計
                planPointCounts += transitStep.pointsCount;
            }
            lineInfo.vehicleInfoArr = busTitleArr;
            lineInfo.lineStepsArr = lineStepsArr;
            lineInfo.stepsArr = stepsArr;
            lineInfo.planPointCounts = planPointCounts;
            [lineArr addObject:lineInfo];
        }
        self.lineStatusArr = lineArr;
        [_tableView reloadData];
    }
}

自駕與步行檢索的結構類似,重點是把每個 step 的入口座標與軌跡點取出來,交給 BMKPolyline 繪製:

- (void)onGetDrivingRouteResult:(BMKRouteSearch*)searcher result:(BMKDrivingRouteResult*)result errorCode:(BMKSearchErrorCode)error {
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        BMKDrivingRouteLine* plan = (BMKDrivingRouteLine*)[result.routes objectAtIndex:0];
        int size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:i];
            if(i==0){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.starting.location;
                item.title = @"起點";
                item.type = 0;
                [_mapView addAnnotation:item];
            }else if(i==size-1){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = @"終點";
                item.type = 1;
                [_mapView addAnnotation:item];
            }
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = transitStep.entrace.location;
            item.title = transitStep.entraceInstruction;
            item.degree = transitStep.direction * 30;
            item.type = 4;
            [_mapView addAnnotation:item];
            planPointCounts += transitStep.pointsCount;
        }
        if (plan.wayPoints) {
            for (BMKPlanNode* tempNode in plan.wayPoints) {
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = tempNode.pt;
                item.type = 5;
                item.title = tempNode.name;
                [_mapView addAnnotation:item];
            }
        }
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKDrivingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
        }
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [_mapView addOverlay:polyLine];
        delete []temppoints;
    }
}

步行檢索:

- (void)onGetWalkingRouteResult:(BMKRouteSearch*)searcher result:(BMKWalkingRouteResult*)result errorCode:(BMKSearchErrorCode)error {
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == BMK_SEARCH_NO_ERROR) {
        BMKWalkingRouteLine* plan = (BMKWalkingRouteLine*)[result.routes objectAtIndex:0];
        int size = [plan.steps count];
        int planPointCounts = 0;
        for (int i = 0; i < size; i++) {
            BMKWalkingStep* transitStep = [plan.steps objectAtIndex:i];
            if(i==0){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.starting.location;
                item.title = @"起點";
                item.type = 0;
                [_mapView addAnnotation:item];
            }else if(i==size-1){
                RouteAnnotation* item = [[RouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = @"終點";
                item.type = 1;
                [_mapView addAnnotation:item];
            }
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = transitStep.entrace.location;
            item.title = transitStep.entraceInstruction;
            item.degree = transitStep.direction * 30;
            item.type = 4;
            [_mapView addAnnotation:item];
            planPointCounts += transitStep.pointsCount;
        }
        BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
        int i = 0;
        for (int j = 0; j < size; j++) {
            BMKWalkingStep* transitStep = [plan.steps objectAtIndex:j];
            int k=0;
            for(k=0;k<transitStep.pointsCount;k++) {
                temppoints[i].x = transitStep.points[k].x;
                temppoints[i].y = transitStep.points[k].y;
                i++;
            }
        }
        BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
        [_mapView addOverlay:polyLine];
        delete []temppoints;
    }
}

四、畫出路徑

我把路線詳情放在另一個控制器裡,先定義需要的資料屬性:

//路線長度
@property (nonatomic,assign) int distance;
//路線消耗時間
@property (nonatomic,assign) int dates;
@property (nonatomic,assign) int hours;
@property (nonatomic,assign) int minutes;
@property (nonatomic,assign) int seconds;
//交通工具數組
@property (nonatomic,strong) NSArray *vehicleInfoArr;
//換乘信息
@property (nonatomic,strong) NSArray *lineStepsArr;
//節點
@property (nonatomic,strong) NSArray *stepsArr;
//軌跡點個數
@property (nonatomic,assign) int planPointCounts;
//軌跡點
@property (nonatomic,strong) NSArray *planStepsArr;

接著是繪製線段與依類型切換圖示:

-(void)drawMap {
    BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
    item = [_lineInfo.stepsArr firstObject];
    [_mapView setCenterCoordinate:item.coordinate];
    [_mapView addAnnotations:_lineInfo.stepsArr];
    BMKMapPoint* temppoints = (BMKMapPoint *)malloc(sizeof(CLLocationCoordinate2D) * _lineInfo.planPointCounts);
    int i = 0;
    for (int j = 0; j < [_lineInfo.planStepsArr count]; j++) {
        BMKTransitStep* transitStep = [_lineInfo.planStepsArr objectAtIndex:j];
        int k=0;
        for(k=0;k<transitStep.pointsCount;k++) {
            temppoints[i].x = transitStep.points[k].x;
            temppoints[i].y = transitStep.points[k].y;
            i++;
        }
    }
    BMKPolyline* polyLine =[BMKPolyline polylineWithPoints:temppoints count:_lineInfo.planPointCounts];
    if (nil != polyLine) {
        [_mapView addOverlay:polyLine];
    }
    free(temppoints);
}
- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)overlay {
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
        BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
        polylineView.fillColor = [[UIColor cyanColor] colorWithAlphaComponent:1];
        polylineView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.7];
        polylineView.lineWidth = 3.0;
        return polylineView;
    }
    return nil;
}
// 判斷標注類型,來處理
- (BMKAnnotationView*)getRouteAnnotationView:(BMKMapView *)mapview viewForAnnotation:(MyBMKPointAnnotation*)routeAnnotation {
    BMKAnnotationView* view = nil;
    switch (routeAnnotation.type) {
        case 0: {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"start_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"start_node"];
                view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_start.png"]];
                view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        } break;
        case 1: {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"end_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"end_node"];
                view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_end.png"]];
                view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5));
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        } break;
        case 2: {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"bus_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"bus_node"];
                view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_bus.png"]];
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        } break;
        case 3: {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"rail_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"rail_node"];
                view.image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_rail.png"]];
                view.canShowCallout = TRUE;
            }
            view.annotation = routeAnnotation;
        } break;
        case 4: {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"route_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"route_node"];
                view.canShowCallout = TRUE;
            } else {
                [view setNeedsDisplay];
            }
            UIImage* image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_direction.png"]];
            view.image = [image imageRotatedByDegrees:routeAnnotation.degree];
            view.annotation = routeAnnotation;
        } break;
        case 5: {
            view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"waypoint_node"];
            if (view == nil) {
                view = [[BMKAnnotationView alloc]initWithAnnotation:routeAnnotation reuseIdentifier:@"waypoint_node"];
                view.canShowCallout = TRUE;
            } else {
                [view setNeedsDisplay];
            }
            UIImage* image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_waypoint.png"]];
            view.image = [image imageRotatedByDegrees:routeAnnotation.degree];
            view.annotation = routeAnnotation;
        } break;
        default: break;
    }
    return view;
}
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation {
    if ([annotation isKindOfClass:[BMKPointAnnotation class]]) {
        return [self getRouteAnnotationView:view viewForAnnotation:(MyBMKPointAnnotation *)annotation];
    }
    return nil;
}
- (UIImage*)imageRotatedByDegrees:(CGFloat)degrees {
    CGFloat width = CGImageGetWidth(self.CGImage);
    CGFloat height = CGImageGetHeight(self.CGImage);
    CGSize rotatedSize;
    rotatedSize.width = width;
    rotatedSize.height = height;
    UIGraphicsBeginImageContext(rotatedSize);
    CGContextRef bitmap = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2);
    CGContextRotateCTM(bitmap, degrees * M_PI / 180);
    CGContextRotateCTM(bitmap, M_PI);
    CGContextScaleCTM(bitmap, -1.0, 1.0);
    CGContextDrawImage(bitmap, CGRectMake(-rotatedSize.width/2, -rotatedSize.height/2, rotatedSize.width, rotatedSize.height), self.CGImage);
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

五、另一種更輕量的寫法

///////////////////////////////
if ([annotation isKindOfClass:[SiteAnnotation class]]) {
    static NSString *identifier = @"MKAnnotationView";
    BMKAnnotationView *pin = [mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
    if (pin == nil) {
        pin = [[BMKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
        pin.image = [UIImage imageNamed:@"default_marker.png"];
    }
    pin.annotation = annotation;
    pin.paopaoView = [[BMKActionPaopaoView alloc]initWithCustomView:[[UIView alloc] init]];
    return pin;
}

實作時有幾個容易忽略的細節:reuseIdentifier 若始終用同一個字串,不同類型的圖示會互相污染,記得依型別區分;BMKMapPoint 陣列是手动 malloc 出來的,用完務必 free;paopaoView 先設 nil 再賦值,是為了避免重用時殘留舊內容。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved