【发布时间】:2019-03-14 21:07:59
【问题描述】:
我想在 uiimagepickercontrollers overlayView 上显示裁剪视图,然后相对于 overlayImage rect 裁剪图像。给定overlayView的矩形,我如何计算裁剪图像?
【问题讨论】:
标签: ios objective-c crop
我想在 uiimagepickercontrollers overlayView 上显示裁剪视图,然后相对于 overlayImage rect 裁剪图像。给定overlayView的矩形,我如何计算裁剪图像?
【问题讨论】:
标签: ios objective-c crop
您可以使用下面的代码块来做到这一点。
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
}
【讨论】:
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!;
}
【讨论】: