問題描述
使用 CGAffineTransformRotate,如何將旋轉設置為 0 (Using CGAffineTransformRotate, how to set rotation to 0)
Giving the following code:
self.transform = CGAffineTransformRotate(self.transform, ?);
Is there a way to set the rotation back to 0 without knowing what the current rotation angle is? I have other transforms that I'd like to maintain, hence why I'm using CGAffineTransformRotate
instead of CGAffineTransformMakeRotation
.
‑‑‑‑‑
參考解法
方法 1:
If it's just scaling and rotation then your options are actually either (i) determine just the scale and make a brand new scaling matrix of that scale; or (ii) as you suggest, determine the rotation and adjust the transform you have by the opposite amount.
You can achieve either by looking at the components of the transform matrix. If you think about how matrix multiplication works you've got the output x axis being (transform.a, transform.b)
and the output y axis being (transform.c, transform.d)
.
So, for (i):
// use the Pythagorean theorem to get the length of either axis;
// that's the scale, e.g.
CGFloat scale = sqrtf(
self.transform.a*self.transform.a +
self.transform.b*self.transform.b);
self.transform = CGAffineTransformMakeScale(scale, scale);
For (ii):
// use arctan to get the rotation of the x axis
CGFloat angle = atan2f(
self.transform.b*self.transform.b, self.transform.b*self.transform.a);
self.transform = CGAffineTransformRotate(self.transform, ‑angle);
方法 2:
You could also invert the transform
CGAffineTransform CGAffineTransformInvert (
CGAffineTransform t
);
eg
self.transform = CGAffineTransformInvert(CGAffineTransformRotate(self.transform, ‑angle));
(by Ser Pounce、Tommy、James Hornitzky)