iOS 圖片裁剪方法


更多圖片處理方法見圖片組件 BBWebImage

iOS 圖片裁剪方法

通過 CGImage 或 CIImage 裁剪

UIImage 有 cgImage 和 ciImage 屬性,分別可以獲得 CGImage 和 CIImage 對象。CGImage 和 CIImage 對象都有裁剪方法,傳入 CGRect 的參數表示要裁剪的區域(采用 UIImage 的坐標)。

static func cropImage(_ image: UIImage, withRect originalRect: CGRect) -> UIImage? {
    if originalRect.width <= 0 || originalRect.height <= 0 { return nil }
    var rect = originalRect
    if image.scale != 1 {
        rect.origin.x *= image.scale
        rect.origin.y *= image.scale
        rect.size.width *= image.scale
        rect.size.height *= image.scale
    }
    if let croppedCgImage = image.cgImage?.cropping(to: rect) {
        return UIImage(cgImage: croppedCgImage)
    } else if let ciImage = image.ciImage {
        let croppedCiImage = ciImage.cropped(to: rect)
        return UIImage(ciImage: croppedCiImage)
    }
    return nil
}

對 CGImage 來說,傳入的 CGRect 參數如果完全不在原圖區域內,cropping(to:) 方法返回空;如果有部分在原圖區域內,cropping(to:) 方法返回在原圖區域部分的 CGImage。

通過位圖(Bitmap)裁剪

通過位圖重新繪制圖片,也可以獲得裁剪之后的圖片。

static func cropImage(_ image: UIImage, withRect rect: CGRect) -> UIImage? {
    if rect.width <= 0 || rect.height <= 0 { return nil }
    UIGraphicsBeginImageContext(rect.size)
    guard let context = UIGraphicsGetCurrentContext() else { return nil }
    context.translateBy(x: -rect.minX, y: -rect.minY)
    image.draw(at: .zero)
    let croppedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return croppedImage
}

位圖大小為需要裁剪區域 CGRect 的大小 size。用原圖繪制,為了使裁剪區域正好在位圖區域,需要進行坐標位移 context.translateBy(x: -rect.minX, y: -rect.minY)

如果傳入的 CGRect 參數有部分或全部不在原圖區域內,則超出原圖區域的部分也會被繪制(繪制為透明),這與 CGImage 的裁剪方法不同。

簡單試了幾次,發現通過 CGImage 裁剪的 CPU 占用率比通過位圖裁剪要低。僅從性能角度考慮,推薦使用前者。如果希望裁剪出來的圖片不超出原圖區域,也推薦使用前者。如果需要繪制其他的內容(比如其他形狀、顏色,或繪制的內容超出原圖區域),則要使用后者。

轉載請注明出處:http://www.cnblogs.com/silence-cnblogs/p/6490037.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM