Reputation: 13941
I have control with animation that rotates image.
I want to start, pause and resume rotation animation at any moment.
I have everything in behind code:
public partial class Wheel32Control : UserControl
{
public Wheel32Control()
{
InitializeComponent();
img.RenderTransform = new RotateTransform();
img.RenderTransformOrigin = new Point(0.5, 0.5);
_daRotate = new DoubleAnimation(0, 360, TimeSpan.FromSeconds(2))
{
RepeatBehavior = RepeatBehavior.Forever
};
}
private DoubleAnimation _daRotate;
private bool _rotate;
public bool Rotate
{
get
{
return _rotate;
}
set
{
_rotate = value;
if (_rotate)
RotateStart();
else
RotateStop();
}
}
private void RotateStart()
{
this.img.RenderTransform.BeginAnimation(RotateTransform.AngleProperty, _daRotate);
}
private void RotateStop()
{
this.img.RenderTransform.BeginAnimation(RotateTransform.AngleProperty, null);
}
}
My XAML part:
<Image Name="img" Source="/Plt;component/Resources/Images/Kolo_32_3.png"
Stretch="None"/>
My problem:
When I stop animation - it "jumps" to "zero point". I want it to stop where it was when I stopped it.
My code sets animation to "null" because I'm new in WPF and this is only way to stop animation I know.
Upvotes: 1
Views: 345
Reputation: 128116
Instead of animating by setting From
and To
, you could animate by a certain amount:
_daRotate = new DoubleAnimation
{
By = 360,
Duration = TimeSpan.FromSeconds(2),
RepeatBehavior = RepeatBehavior.Forever
};
Before removing the animation, set the RotateTransform's Angle
property to the currently animated value. This is done by calling the property getter, which returns the "currently effective property value", and assigning the returned value to the property setter, which sets the "local property value".
private void RotateStop()
{
var rotateTransform = (RotateTransform)img.RenderTransform;
rotateTransform.Angle = rotateTransform.Angle; // looks strange, but works.
rotateTransform.BeginAnimation(RotateTransform.AngleProperty, null);
}
The line
rotateTransform.Angle = rotateTransform.Angle;
might probably better be understandable if you replace it with the code from the CLR wrapper of the Angle
property:
rotateTransform.SetValue(RotateTransform.AngleProperty,
rotateTransform.GetValue(RotateTransform.AngleProperty));
Upvotes: 4