问题
Hi so this is my situation up to now. I've added a UIImageView to Interface Builder and set it to a .png image of a needle (Needle.png), I've also connected it to the corresponding IBOutlet in Xcode.
In my viewDidLoad: method I set the anchor point,
- (void)viewDidLoad {
[super viewDidLoad];
[needle.layer setAnchorPoint:CGPointMake( 0.5, 1 )];
}
And I've also created a button in Interface Builder and connected it to an IBAction in Xcode, this button performs an animation block,
- (IBAction)animate {
[UIView beginAnimations:@"rotate" context:nil];
[UIView setAnimationDuration:1.0];
self.needle.transform = CGAffineTransformMakeRotation(10 * M_PI / 180);
[UIView commitAnimations];
}
So when I press the animate button my needle image rotates by 10° counter-clockwise, so thats a start. But what I really want to do it to have the needle constantly rotating itself to the correct angle based off a constantly changing value.
For example if I have a decibel value that gives me the current decibel level in the room, I'd like that needle to reflect that value (i.e. 10° == 10dB), and since this value is constantly changing I'd want my needle to rotate clockwise or counter-clockwise accordingly.
Does anyone know how I could do that? I'd also appreciate it if someone could post some source code to help me out.
回答1:
But what I really want to do it to have the needle constantly rotating itself to the correct angle based off a constantly changing value.
Change the rotation value when the "constantly changing value" changes.
What is the stimulus to the change of this value? Place the code to change the rotation there.
If the value is a KVO - you could use that mechanism to change the rotation when the KVO changes.
Also - sounds like you may want to do the change in an animation block, to make the needle movements more fluid. Say for example the value only changes once a second - make the change in an animation block that makes it change over the course of a second. They movement of the needle will be less "jerky" that way.
Be forewarned that if you are doing animation, set the setAnimationBeginsFromCurrentState - so if you change values (and re-animate) halfway through an existing animation, it will "do the right thing".
来源:https://stackoverflow.com/questions/4226622/how-to-rotate-a-needle-for-a-sound-level-meter-about-it-origin