ios - 如何裁剪具有 10 像素偏移的图像?

标签 ios swift uiimage

这是我的输入图像:

enter image description here

这就是我需要的输出(没有 10px 填充):

enter image description here

有没有办法在 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) ))
    }

}

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/

相关文章:

ios - 物理主体大于它分配给的纹理(图片)

swift - 如何使用调用回调的函数制作 swift 3.0 类?

ios - UIVIew中的UIButton不在iPhone应用程序中居中

ios - 在 iOS 中使用 Facebook SDK 登录时无法获取用户的电子邮件 ID

ios - 呈现多个 View Controller 的最佳方法? swift 4

ios - 快速检查 viewDidLoad 上的 uiswitch 状态

swift - 如何从窗口 Controller 中引用 View ?

ios - Swift 3 - 如何比较 UIImage 的宽度和高度?

iPhone PNG 加载 alpha 伪影

swift - 创建可以使用图像作为填充的绘图应用程序的最佳方法