5

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

我试图测量比例属性,因为视网膜的比例是 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];

}

提前致谢。

4

1 回答 1

6

我通过将目标大小除以屏幕比例(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;
于 2013-04-08T18:03:35.177 回答