Ios 根据任何视图的框架裁剪图像
我有一个图像,我想根据任何视图的框架进行裁剪。比如, 我真的找不到解决办法。我已经找了两天了 编辑的 感谢@Ajharul Islam和@Bence Pattogato。这两个答案都有效 快速版@Ajharul Islam的解决方案。Ios 根据任何视图的框架裁剪图像,ios,image,crop,Ios,Image,Crop,我有一个图像,我想根据任何视图的框架进行裁剪。比如, 我真的找不到解决办法。我已经找了两天了 编辑的 感谢@Ajharul Islam和@Bence Pattogato。这两个答案都有效 快速版@Ajharul Islam的解决方案。 func images(byCroppingImage image: UIImage?, to size: CGSize) -> UIImage? { // not equivalent to image.size (whic
func images(byCroppingImage image: UIImage?, to size: CGSize) -> UIImage? {
// not equivalent to image.size (which depends on the imageOrientation)!
let refWidth = (image?.cgImage?.width)!
let refHeight = (image?.cgImage?.height)!
let x = (Double(refWidth) - Double(size.width)) / 2
let y = (Double(refHeight) - Double(size.height)) / 2
let cropRect = CGRect(x: CGFloat(x), y: CGFloat(y), width: size.width, height: size.height)
let imageRef = image?.cgImage!.cropping(to: cropRect) as! CGImage
var cropped: UIImage? = nil
if let imageRefs = image?.cgImage!.cropping(to: cropRect) {
cropped = UIImage(cgImage: imageRefs, scale: 0.0, orientation: UIImage.Orientation.up)
}
return cropped
}
让我告诉你我的错误和我想干什么
我试着拍摄照片,并根据任何视图的框架进行裁剪。我试图裁剪图片,但不根据主视图调整大小。所以每次都是从错误的角度切入
我调整了图片的大小,现在我可以成功地裁剪图片。但调整大小会降低图片的质量。所以现在我正在努力寻找最好的方法
谢谢您可以使用以下代码裁剪图像:
- (UIImage *)imageByCroppingImage:(UIImage *)image toSize:(CGSize)size
{
// not equivalent to image.size (which depends on the imageOrientation)!
double refWidth = CGImageGetWidth(image.CGImage);
double refHeight = CGImageGetHeight(image.CGImage);
double x = (refWidth - size.width) / 2.0;
double y = (refHeight - size.height) / 2.0;
CGRect cropRect = CGRectMake(x, y, size.height, size.width);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef scale:0.0 orientation:self.imageOrientation];
CGImageRelease(imageRef);
return cropped;
}
通过图像和视图的矩形,您将从正在搜索的视图中心获得一个裁剪图像
或者。我不确定哪一个更适合您的用例,但它们应该同时工作。例如,您可以这样使用CIPerspectiveCorrection:
(CIImageToWorkWith).applyingFilter("CIPerspectiveCorrection", parameters: [
"inputTopLeft" : CIVector(cgPoint: topleft),
"inputTopRight" : CIVector(cgPoint: topright),
"inputBottomLeft" : CIVector(cgPoint: bottomleft),
"inputBottomRight" : CIVector(cgPoint: bottomright)
])
编辑:您不希望裁剪图像。裁剪就像是在不缩放图像的情况下从图像中剪切某些内容。我认为最简单的方法是:
extension UIImage {
func crop(to rect: CGRect) -> UIImage? {
guard let imageRef = cgImage, let cropped = imageRef.cropping(to: rect) else {
return nil
}
return UIImage(cgImage: cropped)
}
}
您需要导出图像还是仅用于查看?我实际上需要将裁剪后的图像存储在变量中。所以我可以重复使用它。