set TintColor to MKAnnotationView image
I could make this work by capturing an UIView to UIImage:
UIImage *pin = [UIImage imageNamed:@"pin"];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, pin.size.width, pin.size.height)];
imageView.image = [pin imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
imageView.tintColor = [UIColor grayColor]; // set the desired color
// now the magic...
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, imageView.opaque, 0.0);
[imageView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
annotationView.image = img;
There's a better solution than those proposed that doesn't involve creating a UIImageView
.
This Swift code will create a colored version of your UIImage
.
extension UIImage {
func colorized(color : UIColor) -> UIImage {
let rect = CGRectMake(0, 0, self.size.width, self.size.height);
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0);
let context = UIGraphicsGetCurrentContext();
CGContextSetBlendMode(context, .Multiply)
CGContextDrawImage(context, rect, self.CGImage)
CGContextClipToMask(context, rect, self.CGImage)
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let colorizedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return colorizedImage
}
}
Call it like this:
UIImage(named: "myImage")!
.imageWithRenderingMode(.AlwaysTemplate)
.colorized(UIColor.red())
How frustrating. I solved it like this (sans the other property configurations):
-(MKAnnotationView*)annotationView {
MKAnnotationView *annotationView = [[MKAnnotationView alloc] initWithAnnotation: self reuseIdentifier: @"AnnotationIdentifier"];
UIImage *image = [[UIImage imageNamed: @"star"] imageWithRenderingMode: UIImageRenderingModeAlwaysTemplate];
UIImageView *screwYouApple = [[UIImageView alloc] initWithImage: image];
screwYouApple.tintColor = [UIColor redColor];
[annotationView addSubview: screwYouApple];
return annotationView;
}
Basically, I blow off the image
property of the annotationView
and use a properly tinted UIImageView
as a subview
of the annotation.
Variable naming helped the experience be cathartic.