問題描述
Hành vi CGAffineTransformRotate không nhất quán giữa chế độ xem và bộ điều khiển chế độ xem (CGAffineTransformRotate behaviour inconsistent between view and view controller)
I am trying to replicate Music.app's volume thumb reflections. I created a demo project to fine‑tune the maths.
At first, I was animating the views in the controller to keep it simple. After I had done that, I decided to create a custom ReflectedKnobView
so that I could use it in other projects. I copied the relevant code from the controller to the view.
Even though I copied my code exactly as it was in the controller (making relevant modifications) but when I run the app, the view differs in behaviour from the controller.
In the ReflectedKnobView
, the CGAffineTransformRotate()
skews and morphs the views in unpredictable ways.
Code I copied:
‑ (void)updateValues
{
CMRotationRate data = self.mManager.gyroData.rotationRate;
self.xLabel.text = [NSString stringWithFormat:@"%f", RadiansToDegrees(data.x)];
self.yLabel.text = [NSString stringWithFormat:@"%f", RadiansToDegrees(data.y)];
self.zLabel.text = [NSString stringWithFormat:@"%f",RadiansToDegrees(data.z)];
[UIView animateWithDuration:1/20 animations:^{
self.level3Left.transform = CGAffineTransformRotate(self.level3Left.transform, ((data.y / 240) + (data.x / 200)));
self.level3Right.transform = CGAffineTransformRotate(self.level3Right.transform, ((‑1 * data.y) / 240) + (data.x / 200));
}];
}
The level3<Right/Left>
are UIImageView
s.
I suspect that CGAffineTransformRotate()
behaves differently because I am calling it in a view in one case and a controller in another.
Please download the demo project and run it on a device if you don't get what I am saying here.
參考解法
方法 1:
I just did a similar answer on another question How do I calculate the affine translation parameters when rotating a view in iOS?
Here is a rehash of that:
You need to be careful about two things on your rotation‑‑ your anchor point (the point about which the rotation occurs) and the dimensions of the view or viewController.
original view:
If your anchor point is in the corner, it rotates like this:
If your anchor point is in the middle, it rotates like this:
If you have a square layer, view, or view controller, it tends to rotate nicely. A rectangular view will appear to be doing some weird stuff when rotating, but you can adjust for it, if you know the size differences.