Swift如何使用始终1:1的宽高比裁剪图像

时间:2018-02-09 07:48:45

标签: ios swift image crop

我正在使用这个库的裁剪功能来裁剪像Instagram一样的图像。 (https://github.com/fahidattique55/FAImageCropper)它的裁剪部分代码就是这样的。

private func captureVisibleRect() -> UIImage {                       
    var croprect = CGRect.zero
    let xOffset = (scrollView.imageToDisplay?.size.width)! / scrollView.contentSize.width;
    let yOffset = (scrollView.imageToDisplay?.size.height)! / scrollView.contentSize.height;

    croprect.origin.x = scrollView.contentOffset.x * xOffset;
    croprect.origin.y = scrollView.contentOffset.y * yOffset;

    let normalizedWidth = (scrollView?.frame.width)! / (scrollView?.contentSize.width)!
    let normalizedHeight = (scrollView?.frame.height)! / (scrollView?.contentSize.height)!

    croprect.size.width = scrollView.imageToDisplay!.size.width * normalizedWidth
    croprect.size.height = scrollView.imageToDisplay!.size.height * normalizedHeight

    let toCropImage = scrollView.imageView.image?.fixImageOrientation()
    let cr: CGImage? = toCropImage?.cgImage?.cropping(to: croprect)
    let cropped = UIImage(cgImage: cr!)

    return cropped  }

但问题是例如我有一张(800(W)* 600(H))尺寸的照片,我想通过使用全缩放来裁剪全宽。此功能计算裁剪变量(800( W)* 800(H))正确。但是在代码的这一部分let cr: CGImage? = toCropImage?.cgImage?.cropping(to: croprect)之后,cr的分辨率变为(800(W)* 600(H))。如何通过用白色填充空白部分来将其转换为方形图像?

2 个答案:

答案 0 :(得分:1)

我建议您使用UIGraphicsContext绘制一个具有预期宽度和高度的矩形,并用所需的颜色填充它。然后在上面绘制裁剪后的图像。

我没有对此进行过测试,但这应该可以满足您的需求。

我已经省略了代码的其他部分以专注于基本要素。

....
let context: CGContext? = UIGraphicsGetCurrentContext()
let rect = CGRect(x: 0, y: 0, width: width, height: height)
let color = UIColor.white
color.setFill()
context?.fill(rect)

let cr: CGImage? = toCropImage?.cgImage?.cropping(to: croprect)
let cropped = UIImage(cgImage: cr!)

context?.draw(cropped, in: rect)
let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!

用所需的宽度和高度替换宽度和高度。

答案 1 :(得分:1)

您可以使用此链接中的答案在此过程后对图像进行平方。 How to draw full UIImage inside a square with white color on the edge

这是它的Swift 3版本。

private func squareImageFromImage(image: UIImage) -> UIImage{
    var maxSize = max(image.size.width,image.size.height)
    var squareSize = CGSize.init(width: maxSize, height: maxSize)

    var dx = (maxSize - image.size.width) / 2.0
    var dy = (maxSize - image.size.height) / 2.0
    UIGraphicsBeginImageContext(squareSize)
    var rect = CGRect.init(x: 0, y: 0, width: maxSize, height: maxSize)

    var context = UIGraphicsGetCurrentContext()
    context?.setFillColor(UIColor.white.cgColor)
    context?.fill(rect)

    rect = rect.insetBy(dx: dx, dy: dy)
    image.draw(in: rect, blendMode: CGBlendMode.normal, alpha: 1.0)
    var squareImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return squareImage!
}