如何不从中心裁剪图像?

时间:2019-01-10 14:58:39

标签: ios swift

我正在处理要裁剪图像的应用程序。

目前,这是我的裁剪方式:

mainPicture.layer.cornerRadius = mainPicture.frame.size.width / 2
mainPicture.clipsToBounds = true

请求不是从中间裁剪,而是在特定半径和顶部12 px范围内裁剪。

我从正常图像开始: uncropped image

当我当前修剪时,它只是从中间修剪,所以结果是这样的:

cropped image

请求是对其进行裁剪,以使圆的顶部距顶部12 px:

intended crop

这样最终的图像将如下所示:

final intended image

如何使用Swift 4.0做到这一点?

2 个答案:

答案 0 :(得分:3)

这里您需要做的是首先将原始图像从顶部裁剪为具有所需边距的正方形图像(例如20),然后将图像设置为“图像”视图。

以下是您可以在UIImage类上编写的用于裁剪的扩展名:

extension UIImage {
    func getCroppedImage(with topMargin: CGFloat) -> UIImage? {
        let heightWidth = size.height < size.width ? size.height : size.width
        let x = (size.width - heightWidth)/2
        let rect = CGRect(x: x, y: topMargin, width: heightWidth, height: heightWidth)
        if let imageRef = cgImage?.cropping(to: rect) {
            return UIImage(cgImage: imageRef)
        }
        return nil
    }
}

然后在将图像设置为UIImageView之前,请为您的图像调用此方法,例如:

let image = UIImage(named: "test")
imageView.image = image?.getCroppedImage(with: 20)

输出:

这是输入图像:

enter image description here

这是输出:

enter image description here

答案 1 :(得分:1)

通过使用此功能发布图像之前裁剪图像来修复它:

func cropToBounds(image: UIImage, width: CGFloat, height: CGFloat) -> UIImage {

        let cgimage = image.cgImage!
        let contextImage: UIImage = UIImage(cgImage: cgimage)
        let contextSize: CGSize = contextImage.size
        var posX: CGFloat = 0.0
        var posY: CGFloat = 0.0
        var cgwidth: CGFloat = width
        var cgheight: CGFloat = height

        // See what size is longer and create the center off of that
        if contextSize.width > contextSize.height {
            posX = ((contextSize.width - contextSize.height) / 2)
            posY = 0
            cgwidth = contextSize.height
            cgheight = contextSize.height
        } else {
            posX = 0
            posY = (( contextSize.width - contextSize.height) / 2)
            cgwidth = contextSize.width
            cgheight = contextSize.width
        }

        let rect: CGRect = CGRect(x: posX, y: posY, width: cgwidth, height: cgheight)

        // Create bitmap image from context using the rect
        let imageRef: CGImage = cgimage.cropping(to: rect)!

        // Create a new image based on the imageRef and rotate back to the original orientation
        let image: UIImage = UIImage(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation)

        return image
    }