Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image resizing on retina device

I'm developing an app for Mac OS X. I'm trying to resize any NSImage into a specific size like 200x300. It is working fine for Non-retina Mac. But For Retina Mac, it is resizing the image as 400x600 which is just double, as we expected. My project need is to resize the image as per given size regardless, the device on which application is running is retina or non-retina. How can I achieve the target.

I have tried to measure the scale property, as for retina the scale is 2.0 so we are resizing the image for just half of the required.

But when we connected to monitors, one is retina and other is not retina, it again generating the same problem.

Here is the code which I have used for resizing:

-(void)resizeImage:(NSImage *)sourceImage newSize:(CGSize)newSize
{


    NSString *newImagePath = [[[Utility documentPath] stringByAppendingPathComponent:imagefolder] stringByAppendingPathComponent:@"imageName"];



    [sourceImage setScalesWhenResized:YES];
    [sourceImage setSize:newSize];


    NSImage *newImage = [[NSImage alloc] initWithSize:newSize];

    [newImage lockFocus];

    NSRect frame = NSMakeRect(0, 0, newSize.width, newSize.height);

    [NSGraphicsContext saveGraphicsState];

    NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:frame xRadius:0 yRadius:0];
    [path addClip];

    [sourceImage drawInRect:frame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];

    [NSGraphicsContext restoreGraphicsState];

    [newImage unlockFocus];

    CGImageRef CGImage = [newImage CGImageForProposedRect:nil context:nil hints:nil];
    NSBitmapImageRep *imgRep = [[[NSBitmapImageRep alloc] initWithCGImage:CGImage] autorelease];


        NSData *data = [imgRep representationUsingType:NSPNGFileType properties: nil];
        [[NSFileManager defaultManager] createFileAtPath:newImagePath contents:data attributes:nil];

    [newImage release];

}

Thanks in advance.

like image 941
iPhoneDv Avatar asked Feb 18 '13 13:02

iPhoneDv


1 Answers

I solved this problem by dividing the target size by the screen scale (screenScale). ScreenScale is 1.0 on normal screen and 2.0 on retina screens:

CGFloat screenScale = [[NSScreen mainScreen] backingScaleFactor];
float targetScaledWidth = sourceImage.size.width*scale/screenScale;
float targetScaledHeight = sourceImage.size.height*scale/screenScale;
like image 65
Nicolas Lauquin Avatar answered Sep 19 '22 12:09

Nicolas Lauquin