【发布时间】:2017-11-10 05:50:06
【问题描述】:
我得到了 1920x1080 分辨率的图像。我正在尝试将它们裁剪到中心正方形区域(即中心的 1080x1080 正方形)。该决议将来可能会发生变化。可以这样裁剪图像吗?我已经尝试过在 SO 上发布的一些内容,但是如果我尝试裁剪然后居中,我总是会得到一个 660x1080 的图像。这是描绘我想要实现的目标的图像。
基本上红色是原始的,绿色是我想要的,黄色只是显示mixX和midY线。
我试过的代码。
func imageByCroppingImage(image: UIImage, toSize size: CGSize) -> UIImage{
let newCropWidth: CGFloat?
let newCropHeight: CGFloat?
if image.size.width < image.size.height {
if image.size.width < size.width {
newCropWidth = size.width
} else {
newCropWidth = image.size.width
}
newCropHeight = (newCropWidth! * size.height) / size.width
} else {
if image.size.height < size.height {
newCropHeight = size.height
} else {
newCropHeight = image.size.height
}
newCropWidth = (newCropHeight! * size.width) / size.height
}
let x = image.size.width / 2.0 - newCropWidth! / 2.0
let y = image.size.height / 2.0 - newCropHeight! / 2.0
let cropRect = CGRect(x: x, y: y, width: newCropWidth!, height: newCropHeight!)
let imageRef = image.cgImage!.cropping(to: cropRect)
let cropped = UIImage(cgImage: imageRef!, scale: 1.0, orientation: .right)
return cropped
}
然后我将该方法传递给 CGSize(1080, 1080)。我得到的图像是 660、1080。有什么想法吗?
目的是裁剪图像,而不仅仅是居中显示。
【问题讨论】:
-
尝试使用 imageView.center 并分享代码
-
您是要从字面上裁剪原始图像还是将其呈现为正方形?
-
@LeoDabus 试图裁剪它。
-
你可以使用stackoverflow.com/questions/29046571/…而不添加
UIBezierPath(ovalIn: breadthRect).addClip() -
@LeoDabus 我刚刚在测试中意识到这一点。我更新了图像并且它有效。如果您可以将原始评论放在答案中,请接受它。非常感谢。
标签: ios swift swift3 uiimage crop