UIGraphicsBeginImageContextWithOptions模拟macOS

时间:2018-05-05 18:31:27

标签: ios objective-c macos uigraphicscontext

以下是我用于在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中执行此操作的逻辑。

1 个答案:

答案 0 :(得分:0)

经过一番搜索,我发现了一个类似我的问题,但在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代码: