Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

ios - How to apply multiple transforms in Swift

I would like to apply multiple transforms to a UIView (or subclass of UIView), such as translate, rotate, and scale. I know that two transforms can be applied with CGAffineTransformConcat, but how do I do it if I have three or more transforms?

I have seen these questions:

but these questions are asking something different, and the given answers just talk about applying two transforms with CGAffineTransformConcat. Also, they use Objective-C rather than Swift.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can apply multiple transforms by stacking them on top of each other.

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

Or more compactly (but not necessarily as readable):

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

This series of transforms produces the image on the right:

enter image description here

Thanks to this answer for teaching me how to do it.

Notes

  • The order in which you apply the transforms matters. For example, if the transforms were done in the opposite order it would produce the following result.

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

enter image description here

See also

This answer has been tested with Swift 4


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...