最佳答案
您可以使用 Core Graphics cropping裁剪 CGImage
的方法。只需实现一个自定义裁剪方法来取顶部、底部、左侧和右侧,而不是 CGRect
参数,如下所示:
extension CGImage {
var image: UIImage { return .init(cgImage: self) }
func cropping(top: CGFloat, bottom: CGFloat, left: CGFloat, right: CGFloat) -> CGImage? {
let width = CGFloat(self.width)
let height = CGFloat(self.height)
precondition(left + right < width && top + bottom < height)
return cropping(to: .init(origin: .init(x: left, y: top), size: .init(width: width-left-right, height: height-top-bottom) ))
}
}
Playground 测试
let image = UIImage(data: try! Data(contentsOf: URL(string:"http://i.stack.imgur.com/Xs4RX.jpg")!))!
let cropped = image.cgImage?.cropping(top: 100, bottom: 100, left: 100, right: 100)?.image
关于ios - 如何裁剪具有 10 像素偏移的图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58040478/