IOS Swift UIImage裁剪到给定的矩形

时间:2017-11-30 07:36:35

标签: ios swift uiimage crop

我已经尝试将UIImage裁剪为给定的rect但是它没有裁剪常规尺寸 rect size来自scrollView

这里是参考代码:

guard let view = imageCrop else { print("Error"); return }

        let normalizedX = view.contentOffset.x / view.contentSize.width
        let normalizedY = view.contentOffset.y / view.contentSize.height

        let normalizedWidth  = view.frame.width / view.contentSize.width
        let normalizedHeight = view.frame.height / view.contentSize.height

        let cropRect = CGRect(x: normalizedX, y: normalizedY,
                              width: normalizedWidth, height: normalizedHeight)

cropImage(image: imageCrop.image, cropRect: cropRect)



func cropImage(imageToCrop:UIImage, toRect rect:CGRect) -> UIImage{

        let imageRef:CGImage = imageToCrop.cgImage!.cropping(to: rect)!
        let cropped:UIImage = UIImage(cgImage:imageRef)
        return cropped
    }

1 个答案:

答案 0 :(得分:0)

解决。

 var cropArea:CGRect{
        get{
            let factor = imageCrop.image!.size.width/view.frame.width
            let scale = 1/imageCrop.zoomScale
            let imageFrame = imageCrop.frame
            let x = (imageCrop.contentOffset.x + imageCrop.frame.origin.x - imageFrame.origin.x) * scale * factor
            let y = (imageCrop.contentOffset.y + imageCrop.frame.origin.y - imageFrame.origin.y) * scale * factor
            let width = imageCrop.frame.size.width * scale * factor
            let height = imageCrop.frame.size.height * scale * factor
            return CGRect(x: x, y: y, width: width, height: height)
        }
    }