Cómo aplicar múltiples transformaciones en Swift


Me gustaría aplicar múltiples transformaciones a un UIView (o subclase de UIView), como traducir, rotar y escalar. Sé que dos transformaciones se pueden aplicar con CGAffineTransformConcat, pero, ¿cómo lo hago si tengo tres o más transformaciones?

He visto estas preguntas:

Pero estas preguntas están pidiendo algo diferente, y las respuestas dadas solo hablan de aplicar dos transformaciones con CGAffineTransformConcat. Además, utilizan Objective-C en lugar de Swift.

Author: Community, 2015-06-19

2 answers

Puede aplicar varias transformaciones apilándolas una encima de la otra.

var t = CGAffineTransform.identity
t = t.translatedBy(x: 100, y: 300)
t = t.rotated(by: CGFloat.pi / 4)
t = t.scaledBy(x: -1, y: 2)
// ... add as many as you want, then apply it to to the view
imageView.transform = t

O más compacto (pero no necesariamente tan legible):

imageView.transform = CGAffineTransform.identity.translatedBy(x: 100, y: 300).rotated(by: CGFloat.pi / 4).scaledBy(x: -1, y: 2)

Esta serie de transformaciones produce la imagen de la derecha:

introduzca la descripción de la imagen aquí

Gracias a esta respuesta, por enseñarme a hacerlo.

Notas

  • El orden en el que se aplican las transformaciones importa. Por ejemplo, si las transformaciones se hicieron en el orden opuesto, produciría el siguiente resultado.

    t = t.scaledBy(x: -1, y: 2)
    t = t.rotated(by: CGFloat.pi / 4)
    t = t.translatedBy(x: 100, y: 300)
    

introduzca la descripción de la imagen aquí

Véase también

Esta respuesta ha sido probada con Swift 4

 91
Author: Suragch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-06 03:28:53

En Swift 3, estos han sido reemplazados por funciones en CGAffineTransform, que pueden ser encadenadas.

extension CGAffineTransform {
    public func translatedBy(x tx: CGFloat, y ty: CGFloat) -> CGAffineTransform
    public func scaledBy(x sx: CGFloat, y sy: CGFloat) -> CGAffineTransform
    public func rotated(by angle: CGFloat) -> CGAffineTransform
}

Así que por ejemplo

let transform = CGAffineTransform(scaleX: 1.0, y: 3.0).translatedBy(x: 12, y: 9).rotated(by: 17.0)
 19
Author: Tyler Sheaffer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-17 06:36:44