首页 > 解决方案 > macOS 中的 UIGraphicsBeginImageContextWithOptions 模拟

问题描述

这是我用来在 iOS 中缩放图像的代码,即将 500x500 图像缩放到 100x100 图像,然后存储缩放后的副本:

+ (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 中这样做的逻辑。

标签: iosobjective-cmacosuigraphicscontext

解决方案


经过一番搜索,我发现了一个类似我的问题,但在Swift. 所以我把它翻译了Objective-C,就是这样:

+ (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我翻译的代码:


推荐阅读