ios 如何在 Swift 中应用多个转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30929986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to apply multiple transforms in Swift
提问by Suragch
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?
我想对一个UIView
(或 的子类UIView
)应用多个变换,例如平移、旋转和缩放。我知道可以应用两个转换CGAffineTransformConcat
,但是如果我有三个或更多转换,我该怎么做?
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.
但是这些问题提出了一些不同的问题,给出的答案只是谈论使用CGAffineTransformConcat
. 此外,他们使用 Objective-C 而不是 Swift。
回答by Suragch
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 answerfor 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)
应用转换的顺序很重要。例如,如果以相反的顺序进行转换,则会产生以下结果。
t = t.scaledBy(x: -1, y: 2) t = t.rotated(by: CGFloat.pi / 4) t = t.translatedBy(x: 100, y: 300)
See also
也可以看看
- CGAffineTransform Reference(docs)
- Transforms(docs)
- Swift: Translating and Rotating a CGContext, A Visual Explanation (iOS/Xcode)
- Demystifying CGAffineTransform
This answer has been tested with Swift 4
这个答案已经用 Swift 4 测试过
回答by Tyler Sheaffer
In Swift 3, these have been replaced by functions on CGAffineTransform itself, which can be chained.
在 Swift 3 中,这些已经被 CGAffineTransform 本身的函数所取代,它们可以被链接。
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
}
so for example
所以例如
let transform = CGAffineTransform(scaleX: 1.0, y: 3.0).translatedBy(x: 12, y: 9).rotated(by: 17.0)