Search code examples
ioscocoa-touchuiimageviewuislidercgaffinetransform

Preventing CGAffineTransform from applying incrementally


I'm using CGAffineTransformRotate and CGAffineTransformTranslate to animate the progress of a car image (UIImageView) across the screen. The animation is controlled by a UISlider so as the user advances the slider, the car advances and drives around a corner. For each point on the UISlider, I need to be able to set an absolute value for the car's CGAffineTransformRotate and CGAffineTransformTranslate property.

However, each time the transform is called, the car image is being transformed incrementally. So if, for example, I use this at slider point 0.01:

carImage.transform = CGAffineTransformRotate(carImage.transform, degreesToRadians(5));
carImage.transform = CGAffineTransformTranslate(carImage.transform, 4.0, - 10.0);

and this at slider point 0.02:

carImage.transform = CGAffineTransformRotate(carImage.transform, degreesToRadians(10));
carImage.transform = CGAffineTransformTranslate(carImage.transform, 8.0, - 20.0);

When the slider value is 0.02, I would like the car to be at 10 degrees with an x value of 8 and a y value of -20. However, what I'm getting is the car at 15 degrees with an x value of 12 and a y value of -30. It is applying my second transform to the values arrived at after the first transform.

How can I apply each transform to the basic values of my car's UIImageView? Ie I want each transform to be absolute based on the untransformed UIImageView. I do not want the transforms to be incremental.


Solution

  • See if this solve your problem,

    [UIView setAnimationBeginsFromCurrentState:NO];
    

    Another way:
    You can save the previous slider value, and when you change the slider, get the difference between the previous and current slider values, and using that difference calculate the new transformation relative to the previous transformation. For example, if the previous slider value is 0.01 and the current slider value is 0.02, the difference is 0.01 so add 4.0 to the tx and add -10 to ty.