如何快速裁剪始终为1:1宽高比的图像

92vpleto  于 2022-09-19  发布在  Swift
关注(0)|答案(2)|浏览(188)

我正在使用这个库的裁剪功能来裁剪图片,就像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))大小的照片,我想通过使用全变焦来裁剪它的全宽。这个函数正确地计算Croprt变量(800(W)*800(H))。但在代码let cr: CGImage? = toCropImage?.cgImage?.cropping(to: croprect)的这一部分之后,cr的分辨率变为(800(W)*600(H))。我如何通过用白色填充它的空白部分来将其转换为正方形图像?

osh3o9ms

osh3o9ms1#

您可以使用此链接中的答案在此过程后将图像正方形。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!
}
eni9jsuy

eni9jsuy2#

我建议您使用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!

将宽度和高度替换为所需的宽度和高度。

相关问题