簡體   English   中英

將 UIImage 裁剪到中心正方形

[英]Crop UIImage to center square

我得到分辨率為 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。有什么想法嗎?

目的是裁剪圖像,而不僅僅是居中顯示。

您可以使用我在此答案中使用的相同方法,而無需UIBezierPath(ovalIn: breadthRect).addClip()


extension UIImage {
    var isPortrait:  Bool    { size.height > size.width }
    var isLandscape: Bool    { size.width > size.height }
    var breadth:     CGFloat { min(size.width, size.height) }
    var breadthSize: CGSize  { .init(width: breadth, height: breadth) }
    func squared(isOpaque: Bool = false) -> UIImage? {
        guard let cgImage = cgImage?
            .cropping(to: .init(origin: .init(x: isLandscape ? ((size.width-size.height)/2).rounded(.down) : 0,
                                              y: isPortrait  ? ((size.height-size.width)/2).rounded(.down) : 0),
                                size: breadthSize)) else { return nil }
        let format = imageRendererFormat
        format.opaque = isOpaque
        return UIGraphicsImageRenderer(size: breadthSize, format: format).image { _ in
            UIImage(cgImage: cgImage, scale: 1, orientation: imageOrientation)
            .draw(in: .init(origin: .zero, size: breadthSize))
        }
    }
}

let imageURL = URL(string: "http://i.stack.imgur.com/Xs4RX.jpg")!
let image = UIImage(data: try! Data(contentsOf: imageURL))!

let squared = image.squared()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM