Abel
Abel

Reputation: 315

SDWebImage resizing with UIGraphicsBeginImageContextWithOptions

I'm using SDWebImage to download thumbnails. I resize them before caching them by using the - (UIImage *)imageManager:(SDWebImageManager *)imageManager transformDownloadedImage:(UIImage *)image withURL:(NSURL *)imageURL delegate method.

The code i use to reisze images is:

- (UIImage *)imageByScalingAndCroppingForSize:(CGSize)targetSize Image:(UIImage *)image
{
    UIImage *sourceImage = image;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);

    if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;

        if (widthFactor > heightFactor) {
            scaleFactor = widthFactor; // scale to fit height
        } else {
            scaleFactor = heightFactor; // scale to fit width
        }

        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;

        // center the image
        if (widthFactor > heightFactor) {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        } else {
            if (widthFactor < heightFactor) {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
        }
    }

    UIGraphicsBeginImageContextWithOptions(targetSize, YES, 0); // this will crop

    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;

    [sourceImage drawInRect:thumbnailRect];

    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

At first, I used UIGraphicsBeginImageContext(targetSize); but images where blurry on retina deivces so I changed the function to UIGraphicsBeginImageContextWithOptions(targetSize, YES, 0);

But now my images appear much bigger in my TableView cells. It seems the resizing code makes higher definition images but the SDWebImage Library doesn't know how to load them correctly.

Correctly sized images are at the bottom, the top ones don't have the correct size.

Thanks in advance for your help

Upvotes: 0

Views: 430

Answers (1)

Abel
Abel

Reputation: 315

Figured it out,

You can specify the UIImageView that it's loading a retina image by setting the image to UIImage imageWithCGImage:image.CGImage scale:[[UIScreen mainScreen] scale] orientation:image.imageOrientation];

Upvotes: 1

Related Questions