如何裁剪具有 10 像素偏移的图像?
How do I crop the image with 10 pixel offset?
这是我的输入图像:
这就是我需要的 输出(没有 10px 填充):
有没有办法在 Swift 中实现?
您可以使用 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) ))
}
}
游乐场测试
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
这是我的输入图像:
这就是我需要的 输出(没有 10px 填充):
有没有办法在 Swift 中实现?
您可以使用 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) ))
}
}
游乐场测试
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