图像在视网膜设备上调整大小

iPh*_*eDv 4 macos cocoa objective-c nsimage

我正在为Mac OS X开发一个应用程序.我正在尝试将其调整NSImage为特定大小,如200x300.它适用于非视网膜Mac.但对于Retina Mac来说,它正在将图像调整为400x600,这只是我们预期的两倍.我的项目需要是按照给定的大小调整图像大小,无论应用程序运行的设备是视网膜还是非视网膜.我怎样才能达到目标.

我试图测量scale属性,因为视网膜的比例为2.0,所以我们只需要将图像的一半调整大小.

但是当我们连接到监视器时,一个是视网膜,另一个不是视网膜,它再次产生同样的问题.

这是我用于调整大小的代码:

-(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];

}
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Nic*_*uin 5

我通过将目标大小除以屏幕比例(screenScale)来解决了这个问题.ScreenScale在普通屏幕上为1.0,在视网膜屏幕上为2.0:

CGFloat screenScale = [[NSScreen mainScreen] backingScaleFactor];
float targetScaledWidth = sourceImage.size.width*scale/screenScale;
float targetScaledHeight = sourceImage.size.height*scale/screenScale;
Run Code Online (Sandbox Code Playgroud)