裁剪图像在 swift 中的 x 偏移不正确
我已经在输出上获得了正确的长宽比,但是输出奇怪地将裁剪后的图像在 x 轴上正向移动。
预览:
输出:
这是一件非常奇怪的事情,我不确定到底是什么导致了这个结果。为什么 x 偏移不正确?
代码如下:
private func cropImage(image: CGImage, completion: @escaping (_ croppedImage: UIImage) -> Void) {
let aspectRatio: CGFloat = 2208 / 1170
let cropRect = CGRect(x: 0, y: 0, width: CGFloat(image.width), height: CGFloat(image.width) / aspectRatio)
if let croppedImage: CGImage = image.cropping(to: cropRect) {
print("croppedImage: W\(croppedImage.width) H\(croppedImage.height)")
var image: UIImage = UIImage()
if self.currentDevicePosition == .front {
image = UIImage(cgImage: croppedImage, scale: 1.0, orientation: .leftMirrored)
} else {
image = UIImage(cgImage: croppedImage, scale: 1.0, orientation: .right)
}
print("uiimage size: \(image.size)")
completion(image)
}
}
I have gotten the aspect ratio to be correct on the output, however the output oddly moves the cropped image positively on the x axis.
Preview:
Output:
Its a really odd thing to happen, and I am not sure exactly whats causing this result. Why is the x offset incorrect?
Heres the code:
private func cropImage(image: CGImage, completion: @escaping (_ croppedImage: UIImage) -> Void) {
let aspectRatio: CGFloat = 2208 / 1170
let cropRect = CGRect(x: 0, y: 0, width: CGFloat(image.width), height: CGFloat(image.width) / aspectRatio)
if let croppedImage: CGImage = image.cropping(to: cropRect) {
print("croppedImage: W\(croppedImage.width) H\(croppedImage.height)")
var image: UIImage = UIImage()
if self.currentDevicePosition == .front {
image = UIImage(cgImage: croppedImage, scale: 1.0, orientation: .leftMirrored)
} else {
image = UIImage(cgImage: croppedImage, scale: 1.0, orientation: .right)
}
print("uiimage size: \(image.size)")
completion(image)
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是我最终得到的结果。是的,纵横比不同,但这并不影响我原来的问题。我能够修复作物矩形内的 x 偏移量。请注意我如何更改 cgrect 中的“y”?这是因为图像在裁剪后旋转,从而扭转了图像的许多因素。无论如何,这都不是一个优雅的解决方案。其中大部分也是硬编码的,这对我的使用来说很好,因为这些数字实际上永远不需要改变。但尽管如此,我仍在寻找更好的解决方案。
This is what I ended up with. Yes the aspect ratio is different but it does not affect my original question. I was able to fix the x offset within the cropRect. Notice how I changed the "y" in the cgrect? This is because the image is rotated after the crop, reversing many factors to the image. Anyways, this is not an elegant solution by any means. Most of it is also hard coded, which is fine for my use since these numbers will actually never need to change. But nonetheless, I am still searching for a better solution.