如何在 Swift 中应用多个转换 [英] How to apply multiple transforms in Swift

查看:12
本文介绍了如何在 Swift 中应用多个转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对 UIView(或 UIView 的子类)应用多个变换,例如平移、旋转和缩放.我知道两个转换可以应用

感谢

另见

这个答案已经用 Swift 4 测试过

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.

解决方案

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:

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)
    

See also

This answer has been tested with Swift 4

这篇关于如何在 Swift 中应用多个转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆