Latcie
Latcie

Reputation: 701

UIImage aspect fill

I'm trying to perform aspect fill on UIImage (with reusable extension), but I've only got this far:

extension UIImage {
    func resizeToCircleImage(targetSize: CGSize, contentMode: UIViewContentMode) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(targetSize, true, 0.0)
        let rect = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height)
        self.draw(in: rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage!
    }
}

So, this is for an MKAnnotationView.

It end up looking like this:

enter image description here

But I wanted to aspect fit this image:

https://en.wikipedia.org/wiki/Panorama#/media/File:Panorama_of_the_courtyard_of_the_Great_Mosque_of_Kairouan.jpg

Upvotes: 2

Views: 724

Answers (2)

MeGaPk
MeGaPk

Reputation: 149

Swift extension version of code from "karim":

private extension UIImage {

    func resize(to newSize: CGSize) -> UIImage? {
        guard size != newSize else {
            return self
        }
        let imgAspect = size.width/size.height
        let sizeAspect = newSize.width/newSize.height

        let scaledSize: CGSize
        if sizeAspect > imgAspect {
            scaledSize = CGSize(width: newSize.width, height: newSize.width/imgAspect)
        } else {
            scaledSize = CGSize(width: newSize.height * imgAspect, height: newSize.height)
        }

        UIGraphicsBeginImageContextWithOptions(newSize, true, 1.0)
        defer { UIGraphicsEndImageContext() }

        let context = UIGraphicsGetCurrentContext()
        guard let context = context else {
            return nil
        }
        context.clip(to: CGRect(origin: .zero, size: newSize))
        draw(in: CGRect(origin: .zero, size: scaledSize))

        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

Upvotes: 1

karim
karim

Reputation: 15589

Considering a category of UIImage,

- (UIImage *)aspectFillToSize:(CGSize)size
{
    CGFloat imgAspect = self.size.width / self.size.height;
    CGFloat sizeAspect = size.width/size.height;

    CGSize scaledSize;

        if (sizeAspect > imgAspect) { // increase width, crop height
            scaledSize = CGSizeMake(size.width, size.width / imgAspect);
        } else { // increase height, crop width
            scaledSize = CGSizeMake(size.height * imgAspect, size.height);
        }
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextClipToRect(context, CGRectMake(0, 0, size.width, size.height));
    [self drawInRect:CGRectMake(0.0f, 0.0f, scaledSize.width, scaledSize.height)];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

Upvotes: 1

Related Questions