我想在uiimagepickercontrollers overlayView上显示裁剪视图,然后相对于overlayImage rect裁剪图像。给定overlayView的矩形,如何计算裁剪图像?
答案 0 :(得分:0)
private func CropImage( image:UIImage , cropRect:CGRect) -> UIImage
{
UIGraphicsBeginImageContextWithOptions(cropRect.size, false, 0);
let context = UIGraphicsGetCurrentContext();
context?.translateBy(x: 0.0, y: image.size.height);
context?.scaleBy(x: 1.0, y: -1.0);
context?.draw(image.cgImage!, in: CGRect(x:0, y:0, width:image.size.width, height:image.size.height), byTiling: false);
context?.clip(to: [cropRect]);
let croppedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return croppedImage!;
}
答案 1 :(得分:0)
您可以通过使用下面的代码块来实现。
let imageRef:CGImage = uncroppedImage.cgImage!.cropping(to: bounds)!
let croppedImage:UIImage = UIImage(cgImage: imageRef)
在这里您可以根据自己的要求通过考试。
您也可以按照苹果的建议进行操作。
func cropImage(_ inputImage: UIImage, toRect cropRect: CGRect, viewWidth: CGFloat, viewHeight: CGFloat) -> UIImage?
{
let imageViewScale = max(inputImage.size.width / viewWidth,
inputImage.size.height / viewHeight)
// Scale cropRect to handle images larger than shown-on-screen size
let cropZone = CGRect(x:cropRect.origin.x * imageViewScale,
y:cropRect.origin.y * imageViewScale,
width:cropRect.size.width * imageViewScale,
height:cropRect.size.height * imageViewScale)
// Perform cropping in Core Graphics
guard let cutImageRef: CGImage = inputImage.cgImage?.cropping(to:cropZone)
else {
return nil
}
// Return image to UIImage
let croppedImage: UIImage = UIImage(cgImage: cutImageRef)
return croppedImage
}