¿Cómo recortar un UIImage sin perder su propiedad de escala?

Objetivo: recortar un UIImage (que comienza con una propiedad de scale de 2.0)

Realicé el siguiente código:

 let croppedCGImage = originalUIImage.cgImage!.cropping(to: cropRect) let croppedUIImage = UIImage(cgImage: croppedCGImage!) 

Este código funciona, pero el resultado croppedUIImage tiene una propiedad de scale incorrecta de 1.0.


He intentado especificar la scale al crear la image final:

 let croppedUIImage = UIImage(cgImage: croppedCGImage!, scale: 2.0, orientation: .up) 

Esto produce la escala correcta, pero corta las size del size por la mitad incorrectamente.


¿Qué debo hacer aquí?

(* Nota: la propiedad de scale en UIImage es importante porque más tarde UIImagePNGRepresentation(_ image: UIImage) la image con UIImagePNGRepresentation(_ image: UIImage) que se ve afectada por la propiedad de scale )



Editar:

Tengo lo siguiente para trabajar. Desafortunadamente, es sustancialmente más lento que la function de recorte CGImage .

 extension UIImage { func cropping(to rect: CGRect) -> UIImage { UIGraphicsBeginImageContextWithOptions(rect.size, false, self.scale) self.draw(in: CGRect(x: -rect.origin.x, y: -rect.origin.y, width: self.size.width, height: self.size.height)) let croppedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return croppedImage } } 

Prueba esto:

 extension UIImage { func imageByCropToRect(rect:CGRect, scale:Bool) -> UIImage { var rect = rect var scaleFactor: CGFloat = 1.0 if scale { scaleFactor = self.scale rect.origin.x *= scaleFactor rect.origin.y *= scaleFactor rect.size.width *= scaleFactor rect.size.height *= scaleFactor } var image: UIImage? = nil; if rect.size.width > 0 && rect.size.height > 0 { let imageRef = self.cgImage!.cropping(to: rect) image = UIImage(cgImage: imageRef!, scale: scaleFactor, orientation: self.imageOrientation) } return image! } } 

Use esta extensión : –

 extension UIImage { func cropping(to quality: CGInterpolationQuality, rect: CGRect) -> UIImage { UIGraphicsBeginImageContextWithOptions(rect.size, false, self.scale) let context = UIGraphicsGetCurrentContext()! as CGContext context.interpolationQuality = quality let drawRect : CGRect = CGRect(x: -rect.origin.x, y: -rect.origin.y, width: self.size.width, height: self.size.height) context.clip(to: CGRect(x:0, y:0, width: rect.size.width, height: rect.size.height)) self.draw(in: drawRect) let croppedImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return croppedImage } } 

Estoy usando el ImageHelper Pod para iOS y tvOS y funciona perfectamente y también puede satisfacer sus necesidades.

Trae muchas extensiones UIImage como:

Recortar y cambiar el tamaño

 // Crops an image to a new rect func crop(bounds: CGRect) -> UIImage? // Crops an image to a centenetworking square func cropToSquare() -> UIImage? { // Resizes an image func resize(size:CGSize, contentMode: UIImageContentMode = .ScaleToFill) -> UIImage? 

Densidad de pantalla

 // To create an image that is Retina aware, use the screen scale as a multiplier for your size. You should also use this technique for padding or borders. let width = 140 * UIScreen.mainScreen().scale let height = 140 * UIScreen.mainScreen().scale let image = UIImage(named: "myImage")?.resize(CGSize(width: width, height: height)) 

También cosas como: Efectos de image

 // Applies a light blur effect to the image func applyLightEffect() -> UIImage? // Applies a extra light blur effect to the image func applyExtraLightEffect() -> UIImage? // Applies a dark blur effect to the image func applyDarkEffect() -> UIImage? // Applies a color tint to an image func applyTintEffect(tintColor: UIColor) -> UIImage? // Applies a blur to an image based on the specified radius, tint color saturation and mask image func applyBlur(blurRadius:CGFloat, tintColor:UIColor?, saturationDeltaFactor:CGFloat, maskImage:UIImage? = nil) -> UIImage? 
 -(UIImage *)getNeedImageFrom:(UIImage*)image cropRect:(CGRect)rect { CGImageRef subImage = CGImageCreateWithImageInRect(image.CGImage, rect); UIImage *croppedImage = [UIImage imageWithCGImage:subImage]; CGImageRelease(subImage); return croppedImage; } 

vocación

  UIImage *imageSample=image; CGRect rectMake1=CGRectMake(0, 0,imageSample.size.width*1/4, imageSample.size.height); UIImage *img1=[[JRGlobal shanetworkingInstance] getNeedImageFrom:imageSample cropRect:rectMake1];