macOS中的UIGraphicsBeginImageContextWithOptions模拟 [英] UIGraphicsBeginImageContextWithOptions analog in macOS
问题描述
这是我用来在iOS中缩放图像的代码,即将500x500图像缩放到100x100图像,然后存储缩放后的副本:
Here is the code that I'm using to scale images in iOS i.e. scale 500x500 image to 100x100 image and then store scaled copy:
+ (UIImage *)image:(UIImage *)originalImage scaledToSize:(CGSize)desiredSize {
UIGraphicsBeginImageContextWithOptions(desiredSize, YES, [UIScreen mainScreen].scale);
[originalImage drawInRect:CGRectMake(0, 0, desiredSize.width, desiredSize.height)];
UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext;
return finalImage;
}
现在,我需要在macOS应用中实现相同的功能.我怎样才能做到这一点?我看到了这样的问题,但我仍然不明白在macOS中执行此操作的逻辑.
Now I need to implement the same functionality in my macOS app. How can I do that? I saw the question like this but I still can't understand the logic of doing this in macOS.
推荐答案
经过一番搜索,我在 Swift
中发现了一个类似我的问题.所以我将其翻译成 Objective-C
,就是这样:
After some search I found a question like mine but in Swift
. So I translated it in Objective-C
and that's it:
+ (NSImage *)image:(NSImage *)originalImage scaledToSize:(NSSize)desiredSize {
NSImage *newImage = [[NSImage alloc] initWithSize:desiredSize];
[newImage lockFocus];
[originalImage drawInRect:NSMakeRect(0, 0, desiredSize.width, desiredSize.height) fromRect:NSMakeRect(0, 0, imageWidth, imageHeight) operation:NSCompositingOperationSourceOver fraction:1];
[newImage unlockFocus];
newImage.size = desiredSize;
return [[NSImage alloc] initWithData:[newImage TIFFRepresentation]];
}
但是仍然存在一个问题:如果 desiredSize = NSMakeSize(50,50);
,它将返回50 x 50像素.我猜应该是屏幕尺寸的东西.我翻译了 Swift
代码:
But there's still an issue: if desiredSize = NSMakeSize(50,50);
it will return 50 by 50 pixels. It's should be something with screen scale i guess.
There is Swift
code that I translated:
这篇关于macOS中的UIGraphicsBeginImageContextWithOptions模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!