Domanda

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.

È stato utile?

Soluzione

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;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top