ios swift uiimage flip

ios - ¿Cómo voltear UIImage horizontalmente con Swift?



flip (5)

Cambiar el parámetro de orientación de la imagen no es realmente voltear la imagen en todos los casos. La imagen debe ser redibujada de alguna manera ... Por ejemplo, así:

Swift 3

func flipImageLeftRight(_ image: UIImage) -> UIImage? { UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale) let context = UIGraphicsGetCurrentContext()! context.translateBy(x: image.size.width, y: image.size.height) context.scaleBy(x: -image.scale, y: -image.scale) context.draw(image.cgImage!, in: CGRect(origin:CGPoint.zero, size: image.size)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage }

La solución para hacer el cambio de imagen de UIImage es con el código de Objective-C:

[UIImage imageWithCGImage:img.CGImage scale:1.0 orientation: UIImageOrientationDownMirrored]

Sin embargo, imageWithCGImage no está disponible en Swift! ¿Hay una solución para voltear la imagen horizontalmente con Swift? ¡Gracias!


En Swift .... (6.3.1)

YourUIImage.transform = CGAffineTransformMakeScale(-1, 1)

Esto también funciona con un UIView


La mayoría de los métodos de fábrica se convierten en inicializadores de forma rápida. Siempre que esté disponible, incluso si el método de clase aún está disponible, se prefieren. Puedes usar:

init(CGImage cgImage: CGImage!, scale: CGFloat, orientation: UIImageOrientation)

El uso se vería así:

var image = UIImage(CGImage: img.CGImage, scale: 1.0, orientation: .DownMirrored)


Para mí, la forma más sencilla era utilizar el método de instancia de UIImage .withHorizontallyFlippedOrientation() de la siguiente manera:

let flippedImage = straightImage.withHorizontallyFlippedOrientation()

Las frases simples siempre me hacen feliz :)


Swift 4

YOURIMAGEVIEW.transform = CGAffineTransform(scaleX: -1, y: 1)