iOS: How To Create A Resized Image MKAnnotationView

This week, I’ve been working on an app which, as part of it’s functionality, displayed nearby photos from Flickr on a map (see screenshot below).

Since I got the images from Flickr, I didn’t have control of the size of the photo returned. I also actually wanted them to be bigger, so I could also show the photos as a slideshow (which you get to by clicking the SlideShow button).

However, while the MKAnnotationView has an image property, it’s not possible to resize these images. So to get the images to show up resized, I had to subclass MKAnnotationView, add an image view subview of a small size to it, and then display the image in the image view:

//  FlickrImageAnnotationView.h

#import <MapKit/MapKit.h>

@interface FlickrImageAnnotationView : MKAnnotationView

@end
//  FlickrImageAnnotationView.m

#import "FlickrImageAnnotationView.h"

@interface FlickrImageAnnotationView()
{
    UIImageView *_imageView;
}

@end

@implementation FlickrImageAnnotationView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // make sure the x and y of the CGRect are half it's
        // width and height, so the callout shows when user clicks
        // in the middle of the image
        CGRect  viewRect = CGRectMake(-20, -20, 40, 40);
        UIImageView* imageView = [[UIImageView alloc] initWithFrame:viewRect];

        // keeps the image dimensions correct
        // so if you have a rectangle image, it will show up as a rectangle,
        // instead of being resized into a square
        imageView.contentMode = UIViewContentModeScaleAspectFit;

        _imageView = imageView;

        [self addSubview:imageView];
    }
    return self;
}

- (void)setImage:(UIImage *)image
{
    // when an image is set for the annotation view,
    // it actually adds the image to the image view
    _imageView.image = image;
}

@end

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.