大頭針顯示多張圖片

BetterDays發表於2018-05-02

需求:一個大頭針上要顯示文字、圖片1、圖片2、圖片3。

實現思路:設定一個大小適中的superView,把控制元件全部新增到view上,然後把view弄成image,設定給annotation.image即可。

#pragma mark - MAMapViewDelegate
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation{
    if([annotation isKindOfClass:[MAPointAnnotation class]]){
        static NSString *reuseIdentifier = @"annotationReuseIndetifier";
        MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:reuseIdentifier];
        if(annotationView == nil){
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
        }
        annotationView.canShowCallout = NO;
       
        //存放控制元件的view。把view壓成image
        UIView *baseView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 85, 82)];
        //設定偏移量
        carImageView.center = CGPointMake(baseView.centerX, baseView.centerY + 11);
        labelImageView.center = CGPointMake(baseView.centerX, baseView.centerY - 19);
        statusImageView.center = CGPointMake(baseView.centerX, baseView.centerY + 11);
        [baseView addSubview:carImageView];
        [baseView addSubview:labelImageView];
        [baseView addSubview:statusImageView];
        //大頭針的大小是根據image的size來確定的。
        annotationView.image = [self bezierPathClip:baseView];
        return annotationView;
    }
    return nil;
}

//把view弄成圖片
- (UIImage *)bezierPathClip:(UIView *)view{
    UIGraphicsBeginImageContextWithOptions(view.size, NO, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
複製程式碼

相關文章