我正在为 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];
}
提前致谢。
最佳答案
我通过将目标大小除以屏幕比例(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;
关于objective-c - 在 Retina 设备上调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14937116/