我正在使用AlamoFireImage在将用户配置文件图片发送到服务器之前对其进行裁剪。我们的服务器有一些限制,无法发送大于640x640的图像。
我正在使用af_imageAspectScaled UIImage扩展函数,如下所示:
let croppedImage = image.af_imageAspectScaled(
toFill: CGSize(
width: 320,
height: 320
)
)
我原以为这会将
image
裁剪成320px×320px的图像。但是我发现输出图像被保存为640x640px的图像,比例为2.0。下面的XCTest显示了这一点:class UIImageTests: XCTestCase {
func testAfImageAspectScaled() {
if let image = UIImage(
named: "ipad_mini2_photo_1.JPG",
in: Bundle(for: type(of: self)),
compatibleWith: nil
) {
print (image.scale) // prints 1.0
print (image.size) // prints (1280.0, 960.0)
let croppedImage = image.af_imageAspectScaled(
toFill: CGSize(
width: 320,
height: 320
)
)
print (croppedImage.scale) // prints 2.0
print (croppedImage.size) // prints (320.0, 320.0)
}
}
}
我在Xcode 10.2上的iPhone Xr模拟器上运行这个。
原图为1280×960点,比例尺为1,相当于1280×960像素。裁剪后的图像为320×320点,比例为2,相当于640×640像素。
为什么刻度设为2?我能改一下吗?如何生成一个320×320像素的独立于比例和设备的图像?
最佳答案
好吧,检查source code for the af_imageAspectScaled method时,我发现了以下生成实际缩放图像的代码:
UIGraphicsBeginImageContextWithOptions(size, af_isOpaque, 0.0)
draw(in: CGRect(origin: origin, size: scaledSize))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self
UIGraphicsEndImageContext()
值为0.0 on
UIGraphicsBeginImageContextWithOptions
的参数指示使用主屏幕比例因子定义图像大小的方法。我尝试将其设置为1.0,在运行我的测试用例时,
af_imageAspectScaled
生成了一个具有我想要的正确维度的图像。Here有一个显示所有iOS设备分辨率的表。我的应用程序正在为比例因子为2.0的所有设备发送适当大小的图像,但是有几个设备的比例因子为3.0。对于那些应用程序不起作用的人。
好吧,不幸的是,如果我想使用
af_imageAspectScaled
的话,在设置缩放大小时,我需要用设备的比例除以我想要的最终大小,如下所示:let scale = UIScreen.main.scale
let croppedImage = image.af_imageAspectScaled(
toFill: CGSize(
width: 320/scale,
height: 320/scale
)
)
I've sent a pull request to AlamofireImage建议在函数
scale
、af_imageAspectScaled(toFill:)
和af_imageAspectScaled(toFit:)
中添加参数af_imageScaled(to:)
。如果他们接受,上述代码应为:// this is not valid with Alamofire 4.0.0 yet! waiting for my pull request to
// be accepted
let croppedImage = image.af_imageAspectScaled(
toFill: CGSize(
width: 320,
height: 320
),
scale: 1.0
)
// croppedImage would be a 320px by 320px image, regardless of the device type.