ios - 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 中这样做的逻辑。
解决方案
经过一番搜索,我发现了一个类似我的问题,但在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
我翻译的代码:
推荐阅读
- adobe - 访问恢复文件 - InDesign
- django - django-import-export 分配当前用户
- scala - 请求内容长度 265529745 超过了配置的限制 31457280
- javascript - 更改 JS 在 PHP 字符串中不起作用
- docker - Rabbit MQ Docker Image 3.7.6 上未安装 auth_backend_http
- python - 在 python 中保存和加载
- python - 在 lambda 中使用 find() 时出现属性错误
- matplotlib - 如何在 jupyter notebook 中使用非衬线字体制作 matplotlib 绘图?
- python - 将 pandas DataFrame 列添加到行的最佳方法
- node.js - 使用来自 WebPack.DefinePlugin 的全局注入变量进行 NodeJS Mocha 单元测试