public void OpenData(string filename, int number) { // JSON読み込み var wc = new WebClient(); wc.OpenReadCompleted += (_s, _e) => { if (_e.Error == null) { // JSONファイルをMediaクラスのインスタンスに逆シリアル化 var ser = new DataContractJsonSerializer(typeof(MediaData.Media)); try { MediaData.media.Add((MediaData.Media)ser.ReadObject(_e.Result)); debugTextBox.Text = string.Empty; } catch { debugTextBox.Text = "JSONファイルの記述に誤りがあります.:" + filename; return; } // 動画ソースへ var movieSet = new MediaData.MovieSet(); movieSet.viewList = new Dictionary <string, AdaptMediaPlayer.Controls.MediaPlayer>(); movieSet.playerPosition = number; for (var urlPos = 0; urlPos < MediaData.media[MediaData.media.Count - 1].video.Count; urlPos++) { var player = new Controls.MediaPlayer(); player.sb = new Storyboard { Duration = TimeSpan.FromMinutes(30) // 時間は適当 }; // Mediaとひも付け player.media = MediaData.media[MediaData.media.Count - 1]; player.movie.Source = new Uri(MediaData.baseUri, player.media.video[urlPos].url); player.title.Text = player.media.title; player.movie_index = MediaData.media.Count - 1; player.Margin = new Thickness(8, 8, 0, 0); Canvas.SetLeft(player, 340 * number); Canvas.SetTop(player, 0); // JSONからアニメーションを生成 // rectangle編 foreach (var value in player.media.video[0].rectangle) // 決め打ち { // 四角を作る var rect = new Rectangle { Height = value.height[0], Width = value.width[0], Stroke = new SolidColorBrush(TransColor(value.color)), StrokeThickness = 2, Visibility = Visibility.Collapsed }; Canvas.SetLeft(rect, value.left[0]); Canvas.SetTop(rect, value.top[0]); player.anime.Children.Add(rect); // アニメの定義 var anim = new ObjectAnimationUsingKeyFrames(); // 四角を出す var frame1 = new DiscreteObjectKeyFrame(); frame1.KeyTime = TimeSpan.Zero; frame1.Value = Visibility.Visible; // 四角を消す var frame2 = new DiscreteObjectKeyFrame(); frame2.KeyTime = TimeSpan.Parse(value.time[value.time.Count - 1]) - TimeSpan.Parse(value.time[0]); frame2.Value = Visibility.Collapsed; anim.KeyFrames.Add(frame1); anim.KeyFrames.Add(frame2); anim.BeginTime = TimeSpan.Parse(value.time[0]); // Storyboardの定義 player.sb.Children.Add(anim); Storyboard.SetTarget(anim, rect); Storyboard.SetTargetProperty(anim, new PropertyPath(VisibilityProperty)); // 長方形の変形・移動を設定する if (value.height.Count >= 2) { var animeHeight = new DoubleAnimationUsingKeyFrames(); var animeWidth = new DoubleAnimationUsingKeyFrames(); var animeLeft = new DoubleAnimationUsingKeyFrames(); var animeTop = new DoubleAnimationUsingKeyFrames(); for (var i = 1; i < value.time.Count; i++) { // 四角の変形 : Height var animeHeightKeyFrame = new LinearDoubleKeyFrame { KeyTime = TimeSpan.Parse(value.time[i]), Value = value.height[i] }; animeHeight.KeyFrames.Add(animeHeightKeyFrame); // 四角の変形 : Width var animeWidthKeyFrame = new LinearDoubleKeyFrame { KeyTime = TimeSpan.Parse(value.time[i]), Value = value.width[i] }; animeWidth.KeyFrames.Add(animeWidthKeyFrame); // 四角の移動 : Left var animeLeftKeyFrame = new LinearDoubleKeyFrame { KeyTime = TimeSpan.Parse(value.time[i]), Value = value.left[i] }; animeLeft.KeyFrames.Add(animeLeftKeyFrame); // 四角の移動 : Top var animeTopKeyFrame = new LinearDoubleKeyFrame { KeyTime = TimeSpan.Parse(value.time[i]), Value = value.top[i] }; animeTop.KeyFrames.Add(animeTopKeyFrame); } player.sb.Children.Add(animeHeight); Storyboard.SetTarget(animeHeight, rect); Storyboard.SetTargetProperty(animeHeight, new PropertyPath(Rectangle.HeightProperty)); player.sb.Children.Add(animeWidth); Storyboard.SetTarget(animeWidth, rect); Storyboard.SetTargetProperty(animeWidth, new PropertyPath(Rectangle.WidthProperty)); player.sb.Children.Add(animeLeft); Storyboard.SetTarget(animeLeft, rect); Storyboard.SetTargetProperty(animeLeft, new PropertyPath(Canvas.LeftProperty)); player.sb.Children.Add(animeTop); Storyboard.SetTarget(animeTop, rect); Storyboard.SetTargetProperty(animeTop, new PropertyPath(Canvas.TopProperty)); } } // text編 foreach (var value in player.media.video[0].text) // 決め打ち { // テキストを作る var str = new TextBlock { Text = value.text, FontSize = 18, Foreground = new SolidColorBrush(TransColor(value.color)), Visibility = Visibility.Collapsed }; Canvas.SetLeft(str, value.left[0]); Canvas.SetTop(str, value.top[0]); player.anime.Children.Add(str); // アニメの定義 var anim = new ObjectAnimationUsingKeyFrames(); // テキストを出す var frame1 = new DiscreteObjectKeyFrame(); frame1.KeyTime = TimeSpan.Zero; frame1.Value = Visibility.Visible; // テキストを消す var frame2 = new DiscreteObjectKeyFrame(); frame2.KeyTime = TimeSpan.Parse(value.time[1]) - TimeSpan.Parse(value.time[0]); frame2.Value = Visibility.Collapsed; anim.KeyFrames.Add(frame1); anim.KeyFrames.Add(frame2); anim.BeginTime = TimeSpan.Parse(value.time[0]); // Storyboardの定義 player.sb.Children.Add(anim); Storyboard.SetTarget(anim, str); Storyboard.SetTargetProperty(anim, new PropertyPath(VisibilityProperty)); } // プレイヤーを追加 playerArea.Children.Add(player); // 最初に表示するプレイヤーを決定 movieSet.viewList.Add(player.media.video[urlPos].viewpoint, player); if (urlPos == 0) { movieSet.currentPlayer = player; } else { player.Visibility = Visibility.Collapsed; } } MediaData.movieList.Add(movieSet); // カメラ切替ボタン生成 if (MediaData.media.Count == 1) { foreach (var value in MediaData.media[0].video) // 決め打ち { var buttonChange = new Button { Content = value.viewpoint, FontSize = 18, Width = 80 }; Canvas.SetTop(buttonChange, 35 * MediaData.media[0].video.IndexOf(value)); // 決め打ち buttonChange.Click += new RoutedEventHandler(ChangeCamera); ChangeCameraArea.Children.Add(buttonChange); var buttonEx = new Button { Content = value.viewpoint, FontSize = 18, Width = 80 }; Canvas.SetTop(buttonEx, 35 * (MediaData.media[0].video.IndexOf(value) + 1)); // 決め打ち buttonEx.Click += new RoutedEventHandler(ExCamera); ExCamaraArea.Children.Add(buttonEx); } } // JSON変更ボタン var openJsonButton = new Image { Source = new BitmapImage(new Uri("../image/Open.png", UriKind.Relative)), Height = 24, Width = 24, Margin = new Thickness(8, 8, 0, 0), Tag = movieSet.playerPosition }; Canvas.SetLeft(openJsonButton, 288 + 340 * movieSet.playerPosition); openJsonButton.MouseLeftButtonDown += new MouseButtonEventHandler(OpenJsonFile); openFileButtonArea.Children.Add(openJsonButton); } else { // エラー処理 debugTextBox.Text = _e.Error.ToString(); } }; wc.OpenReadAsync(new Uri(MediaData.baseUri, filename)); }
/// <summary> /// Start object animation. /// </summary> /// <param name="parent">Object that contains property.</param> /// <param name="propertyName">A name of the property.</param> /// <param name="obj">Object that will animated. Using in case if @propertyName is null.</param> /// <param name="propertyPath">A path that describe the dependency property to be animated.</param> /// <param name="duration">How many time would take transit.</param> /// <param name="from">Start value.</param> /// <param name="to">Finish value.</param> /// <param name="fillBehavior"> /// Specifies how a System.Windows.Media.Animation.Timeline behaves when it is outside /// its active period but its parent is inside its active or hold period.</param> /// <param name="initHandler">Handler that would be called before animation start. /// There you can subscrube on events or reconfigurate settigns.</param> /// <returns>Created storyboard.</returns> private static Storyboard StartStoryboard( FrameworkElement parent, string propertyName, DependencyObject obj, PropertyPath propertyPath, TimeSpan duration, object from, object to, FillBehavior fillBehavior, Action <Storyboard> initHandler) { // Create a storyboard to contains the animations. Storyboard storyboard = new Storyboard { FillBehavior = fillBehavior }; // Add the animation to the storyboard ObjectAnimationUsingKeyFrames animation = new ObjectAnimationUsingKeyFrames(); storyboard.Children.Add(animation); animation.Duration = new Duration(duration); animation.AccelerationRatio = 1.0f; // Set start position. DiscreteObjectKeyFrame startKey = new DiscreteObjectKeyFrame( from, KeyTime.FromPercent(0)); // Set finish position. DiscreteObjectKeyFrame finishKey = new DiscreteObjectKeyFrame( to, KeyTime.FromPercent(1)); // Configure the animation to target de property Opacity if (string.IsNullOrEmpty(propertyName)) { Storyboard.SetTarget(animation, obj); } else { Storyboard.SetTargetName(animation, propertyName); } Storyboard.SetTargetProperty(animation, propertyPath); // Add keys. animation.KeyFrames.Add(startKey); //animation.KeyFrames.Add(middleKey); animation.KeyFrames.Add(finishKey); // Inform subscribers. initHandler?.Invoke(storyboard); // Begin the storyboard try { storyboard.Begin(parent); } catch (Exception ex) { MessageBox.Show(ex.Message); } return(storyboard); }
private void AnimateSource() { if (_image == null) { return; } var source = _image.Source; var decoder = GetGifBitmapDecoder(source); if (decoder != null) { var bitmapFrames = decoder.Frames; var storyboard = new Storyboard(); var animation = new ObjectAnimationUsingKeyFrames { RepeatBehavior = RepeatBehavior.Forever }; var frameMetadatas = bitmapFrames.Select(GetGifFrameMetadata).ToList(); var timeSpan = TimeSpan.Zero; var width = decoder.Metadata.GetQueryOrDefault <ushort>("/logscrdesc/Width"); var height = decoder.Metadata.GetQueryOrDefault <ushort>("/logscrdesc/Height"); for (var i = 0; i < bitmapFrames.Count; i++) { var bitmapFrame = bitmapFrames[i]; var frameMetadata = frameMetadatas[i]; var discreteObjectKeyFrame = new DiscreteObjectKeyFrame { KeyTime = timeSpan }; var drawingVisual = new DrawingVisual(); using (var drawingContext = drawingVisual.RenderOpen()) { DrawGifFrame(drawingContext, bitmapFrames, frameMetadatas, i); } var renderTargetBitmap = new RenderTargetBitmap(width, height, bitmapFrame.DpiX, bitmapFrame.DpiY, PixelFormats.Pbgra32); renderTargetBitmap.Render(drawingVisual); discreteObjectKeyFrame.Value = renderTargetBitmap; animation.KeyFrames.Add(discreteObjectKeyFrame); timeSpan += frameMetadata.Delay; } animation.Duration = timeSpan; Storyboard.SetTarget(animation, _image); Storyboard.SetTargetProperty(animation, new PropertyPath(nameof(_image.Source))); storyboard.Children.Add(animation); storyboard.Begin(); } else { _image.BeginAnimation(Image.SourceProperty, null); _image.Source = source; } }
/// <summary> /// Animation code for the image changing /// </summary> private void DisplayNextImage(Image img) { const double transition_time = 0.9; Storyboard sb = new Storyboard(); // *************************** // Animate Opacity 1.0 --> 0.0 // *************************** DoubleAnimation fade_out = new DoubleAnimation(1.0, 0.0, TimeSpan.FromSeconds(transition_time)) { BeginTime = TimeSpan.FromSeconds(0) }; // Use the Storyboard to set the target property. Storyboard.SetTarget(fade_out, img); Storyboard.SetTargetProperty(fade_out, new PropertyPath(Image.OpacityProperty)); // Add the animation to the StoryBoard. sb.Children.Add(fade_out); // ********************************* // Animate displaying the new image. // ********************************* ObjectAnimationUsingKeyFrames new_image_animation = new ObjectAnimationUsingKeyFrames { // Start after the first animation has finisheed. BeginTime = TimeSpan.FromSeconds(transition_time) }; // Add a key frame to the animation. // It should be at time 0 after the animation begins. DiscreteObjectKeyFrame new_image_frame = new DiscreteObjectKeyFrame(Images[ImageNumber], TimeSpan.Zero); new_image_animation.KeyFrames.Add(new_image_frame); // Use the Storyboard to set the target property. Storyboard.SetTarget(new_image_animation, img); Storyboard.SetTargetProperty(new_image_animation, new PropertyPath(Image.SourceProperty)); // Add the animation to the StoryBoard. sb.Children.Add(new_image_animation); // *************************** // Animate Opacity 0.0 --> 1.0 // *************************** // Start when the first animation ends. DoubleAnimation fade_in = new DoubleAnimation(0.0, 1.0, TimeSpan.FromSeconds(transition_time)) { BeginTime = TimeSpan.FromSeconds(transition_time) }; // Use the Storyboard to set the target property. Storyboard.SetTarget(fade_in, img); Storyboard.SetTargetProperty(fade_in, new PropertyPath(Image.OpacityProperty)); // Add the animation to the StoryBoard. sb.Children.Add(fade_in); // Start the storyboard on the img control. sb.Begin(img); }
private static ObjectAnimationUsingKeyFrames GetAnimation(Image imageControl, BitmapSource source) { var animation = AnimationCache.GetAnimation(source, GetRepeatBehavior(imageControl)); if (animation != null) { return(animation); } GifFile gifMetadata; var decoder = GetDecoder(source, out gifMetadata) as GifBitmapDecoder; if (decoder != null && decoder.Frames.Count > 1) { var fullSize = GetFullSize(decoder, gifMetadata); int index = 0; animation = new ObjectAnimationUsingKeyFrames(); var totalDuration = TimeSpan.Zero; BitmapSource baseFrame = null; foreach (var rawFrame in decoder.Frames) { var metadata = GetFrameMetadata(decoder, gifMetadata, index); var frame = MakeFrame(fullSize, rawFrame, metadata, baseFrame); var keyFrame = new DiscreteObjectKeyFrame(frame, totalDuration); animation.KeyFrames.Add(keyFrame); totalDuration += metadata.Delay; switch (metadata.DisposalMethod) { case FrameDisposalMethod.None: case FrameDisposalMethod.DoNotDispose: baseFrame = frame; break; case FrameDisposalMethod.RestoreBackground: if (IsFullFrame(metadata, fullSize)) { baseFrame = null; } else { baseFrame = ClearArea(frame, metadata); } break; case FrameDisposalMethod.RestorePrevious: // Reuse same base frame break; } index++; } animation.Duration = totalDuration; animation.RepeatBehavior = GetActualRepeatBehavior(imageControl, decoder, gifMetadata); AnimationCache.AddAnimation(source, GetRepeatBehavior(imageControl), animation); AnimationCache.IncrementReferenceCount(source, GetRepeatBehavior(imageControl)); return(animation); } return(null); }
public static void RemoveAnimation(ImageSource source, RepeatBehavior repeatBehavior, ObjectAnimationUsingKeyFrames animation) { var key = new CacheKey(source, repeatBehavior); AnimationCacheDic.Remove(key); }
private static void Show(Popup popup, Action complete = null, double height = 40) { if (!(popup.Child.RenderTransform is CompositeTransform)) { popup.Child.RenderTransform = new CompositeTransform(); } ((CompositeTransform)popup.Child.RenderTransform).TranslateY = -height; Debug.Assert(popup.Child is FrameworkElement); var element = popup.Child as FrameworkElement; element.Height = height; var storyboard = new Storyboard { AutoReverse = false }; var doubleAnimaionUsingKeyFrames = new DoubleAnimationUsingKeyFrames(); Storyboard.SetTarget(doubleAnimaionUsingKeyFrames, popup.Child); Storyboard.SetTargetProperty(doubleAnimaionUsingKeyFrames, "(UIElement.Opacity)"); storyboard.Children.Add(doubleAnimaionUsingKeyFrames); //0.5秒透明度从0-1 var doubleKeyFrame = new EasingDoubleKeyFrame { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.5)), Value = 1, EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut } }; doubleAnimaionUsingKeyFrames.KeyFrames.Add(doubleKeyFrame); doubleKeyFrame = new EasingDoubleKeyFrame { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2.4)), Value = 0.995, EasingFunction = new CubicEase { EasingMode = EasingMode.EaseIn } }; doubleAnimaionUsingKeyFrames.KeyFrames.Add(doubleKeyFrame); doubleKeyFrame = new EasingDoubleKeyFrame { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(3)), Value = 0.1, }; doubleAnimaionUsingKeyFrames.KeyFrames.Add(doubleKeyFrame); doubleAnimaionUsingKeyFrames = new DoubleAnimationUsingKeyFrames(); Storyboard.SetTarget(doubleAnimaionUsingKeyFrames, popup.Child); Storyboard.SetTargetProperty(doubleAnimaionUsingKeyFrames, "(UIElement.RenderTransform).(CompositeTransform.TranslateY)"); storyboard.Children.Add(doubleAnimaionUsingKeyFrames); doubleKeyFrame = new EasingDoubleKeyFrame { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0.5)), Value = 0, EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut } }; doubleAnimaionUsingKeyFrames.KeyFrames.Add(doubleKeyFrame); doubleKeyFrame = new EasingDoubleKeyFrame { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(2.4)), Value = 0, }; doubleAnimaionUsingKeyFrames.KeyFrames.Add(doubleKeyFrame); doubleKeyFrame = new EasingDoubleKeyFrame { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(3)), Value = -height, EasingFunction = new CubicEase { EasingMode = EasingMode.EaseIn } }; doubleAnimaionUsingKeyFrames.KeyFrames.Add(doubleKeyFrame); var objectAnimaionUsingKeyFrames = new ObjectAnimationUsingKeyFrames(); Storyboard.SetTarget(objectAnimaionUsingKeyFrames, popup); Storyboard.SetTargetProperty(objectAnimaionUsingKeyFrames, "(Popup.IsOpen)"); storyboard.Children.Add(objectAnimaionUsingKeyFrames); var discreteObjectKeyFrame = new DiscreteObjectKeyFrame { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = true }; objectAnimaionUsingKeyFrames.KeyFrames.Add(discreteObjectKeyFrame); discreteObjectKeyFrame = new DiscreteObjectKeyFrame { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(3)), Value = false }; objectAnimaionUsingKeyFrames.KeyFrames.Add(discreteObjectKeyFrame); if (complete != null) { storyboard.Completed += (s, e) => complete.Invoke(); } storyboard.Begin(); }
private static void InitAnimationOrImage(Image imageControl) { var controller = GetAnimationController(imageControl); if (controller != null) { controller.Dispose(); } SetAnimationController(imageControl, null); BitmapSource source = GetAnimatedSource(imageControl) as BitmapSource; bool isInDesignMode = DesignerProperties.GetIsInDesignMode(imageControl); bool animateInDesignMode = GetAnimateInDesignMode(imageControl); bool shouldAnimate = !isInDesignMode || animateInDesignMode; // For a BitmapImage with a relative UriSource, the loading is deferred until // BaseUri is set. This method will be called again when BaseUri is set. bool isLoadingDeferred = IsLoadingDeferred(source); if (source != null && shouldAnimate && !isLoadingDeferred) { // Case of image being downloaded: retry after download is complete if (source.IsDownloading) { EventHandler handler = null; handler = (sender, args) => { source.DownloadCompleted -= handler; InitAnimationOrImage(imageControl); }; source.DownloadCompleted += handler; imageControl.Source = source; return; } GifFile gifMetadata; var decoder = GetDecoder(source, out gifMetadata) as GifBitmapDecoder; if (decoder != null && decoder.Frames.Count > 1) { var fullSize = GetFullSize(decoder, gifMetadata); int index = 0; var animation = new ObjectAnimationUsingKeyFrames(); var totalDuration = TimeSpan.Zero; BitmapSource baseFrame = null; foreach (var rawFrame in decoder.Frames) { var metadata = GetFrameMetadata(decoder, gifMetadata, index); var frame = MakeFrame(fullSize, rawFrame, metadata, baseFrame); var keyFrame = new DiscreteObjectKeyFrame(frame, totalDuration); animation.KeyFrames.Add(keyFrame); totalDuration += metadata.Delay; switch (metadata.DisposalMethod) { case FrameDisposalMethod.None: case FrameDisposalMethod.DoNotDispose: baseFrame = frame; break; case FrameDisposalMethod.RestoreBackground: if (IsFullFrame(metadata, fullSize)) { baseFrame = null; } else { baseFrame = ClearArea(frame, metadata); } break; case FrameDisposalMethod.RestorePrevious: // Reuse same base frame break; } index++; } animation.Duration = totalDuration; animation.RepeatBehavior = GetActualRepeatBehavior(imageControl, decoder, gifMetadata); if (animation.KeyFrames.Count > 0) { // For some reason, it sometimes throws an exception the first time... the second time it works. TryTwice(() => imageControl.Source = (ImageSource)animation.KeyFrames[0].Value); } else { imageControl.Source = decoder.Frames[0]; } controller = new ImageAnimationController(imageControl, animation, GetAutoStart(imageControl)); SetAnimationController(imageControl, controller); return; } } imageControl.Source = source; }
/// <summary> /// The animate to. /// </summary> /// <param name="target"> /// The target. /// </param> /// <param name="propertyName"> /// The property name. /// </param> /// <param name="value"> /// The value. /// </param> /// <param name="duration"> /// The duration. /// </param> /// <param name="increment"> /// The increment. /// </param> /// <exception cref="ArgumentException"> /// </exception> internal static void AnimateTo( FrameworkElement target, string propertyName, object value, Duration duration, bool increment) { if (!string.IsNullOrEmpty(propertyName) && target != null) { PropertyInfo property = target.GetType().GetProperty(propertyName); if (property == null) { throw new ArgumentException( "Cannot find property " + propertyName + " on object " + target.GetType().Name); } if (!property.CanWrite) { throw new ArgumentException( "Property is read-only " + propertyName + " on object " + target.GetType().Name); } object toValue = value; TypeConverter typeConverter = ConverterHelper.GetTypeConverter(property.PropertyType); Exception innerException = null; try { if (((typeConverter != null) && (value != null)) && typeConverter.CanConvertFrom(value.GetType())) { toValue = typeConverter.ConvertFrom(value); } object fromValue = property.GetValue(target, null); if (increment) { toValue = Add(toValue, fromValue); } if (duration.HasTimeSpan) { Timeline timeline = null; if ((typeof(FrameworkElement).IsAssignableFrom(target.GetType()) && ((propertyName == "Width") || (propertyName == "Height"))) && double.IsNaN((double)fromValue)) { fromValue = propertyName == "Width" ? target.ActualWidth : target.ActualHeight; } var storyboard = new Storyboard(); if (typeof(double).IsAssignableFrom(property.PropertyType)) { var animation = new DoubleAnimation { From = (double)fromValue }; if (toValue != null) { var actualVal = Double.NaN; Double.TryParse(toValue.ToString(), out actualVal); animation.To = actualVal; } timeline = animation; } else if (typeof(Color).IsAssignableFrom(property.PropertyType)) { var animation2 = new ColorAnimation { From = (Color)fromValue }; if (toValue != null) { animation2.To = (Color)toValue; } timeline = animation2; } else if (typeof(Point).IsAssignableFrom(property.PropertyType)) { if (toValue != null) { var animation3 = new PointAnimation { From = (Point)fromValue, To = (Point)toValue }; timeline = animation3; } } else { var frames = new ObjectAnimationUsingKeyFrames(); var frame = new DiscreteObjectKeyFrame { KeyTime = KeyTime.FromTimeSpan(new TimeSpan(0L)), Value = fromValue }; var frame2 = new DiscreteObjectKeyFrame { KeyTime = KeyTime.FromTimeSpan(duration.TimeSpan), Value = toValue }; frames.KeyFrames.Add(frame); frames.KeyFrames.Add(frame2); timeline = frames; } if (timeline != null) { timeline.Duration = duration; storyboard.Children.Add(timeline); } Storyboard.SetTarget(storyboard, target); Storyboard.SetTargetProperty(storyboard, new PropertyPath(property.Name, new object[0])); storyboard.Begin(); } else { property.SetValue(target, toValue, new object[0]); } } catch (FormatException exception2) { innerException = exception2; } catch (ArgumentException exception3) { innerException = exception3; } catch (MethodAccessException exception4) { innerException = exception4; } if (innerException != null) { throw new ArgumentException(innerException.Message); } } }
public ObjectAnimationUsingKeyFrames CreateArmAnimation(double startTime, Button btn, int idx) { var deal_style = Setting.Instance.GetStrSetting("deal_style"); ObjectAnimationUsingKeyFrames armChgBg = new ObjectAnimationUsingKeyFrames(); DiscreteObjectKeyFrame deal1 = new DiscreteObjectKeyFrame(); deal1.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startTime)); deal1.Value = images[1]; DiscreteObjectKeyFrame deal2 = new DiscreteObjectKeyFrame(); deal2.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startTime + 0.4)); deal2.Value = images[4]; //DiscreteObjectKeyFrame dk1 = new DiscreteObjectKeyFrame(); //dk1.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startTime + 0.8)); //dk1.Value = images[4]; armChgBg.KeyFrames.Add(deal1); armChgBg.KeyFrames.Add(deal2); if (deal_style == "直接开牌1") //手不回到桌下 { var count = Game.Instance.CurrentRound.HandCard[0].Count + Game.Instance.CurrentRound.HandCard[1].Count; if (idx < 3) { DiscreteObjectKeyFrame hold = new DiscreteObjectKeyFrame(); hold.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startTime + 0.9)); hold.Value = images[1]; armChgBg.KeyFrames.Add(hold); } else { DiscreteObjectKeyFrame back = new DiscreteObjectKeyFrame(); back.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startTime + 0.9)); back.Value = images[0]; armChgBg.KeyFrames.Add(back); } //if ( idx == count - 1) //如果是最后一张 //{ // //DiscreteObjectKeyFrame hold = new DiscreteObjectKeyFrame(); // //hold.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startTime + 0.9)); // //hold.Value = images[1]; // //armChgBg.KeyFrames.Add(hold); // if (idx == 5) // { // DiscreteObjectKeyFrame back = new DiscreteObjectKeyFrame(); // back.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startTime + 1)); // back.Value = images[0]; // armChgBg.KeyFrames.Add(back); // } // else // { // startTime = reverse_start_time[idx] ; // DiscreteObjectKeyFrame back = new DiscreteObjectKeyFrame(); // back.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startTime)); // back.Value = images[0]; // armChgBg.KeyFrames.Add(back); // } //} } else if (deal_style == "直接开牌2") //手回到桌下 { DiscreteObjectKeyFrame back = new DiscreteObjectKeyFrame(); back.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startTime + 0.9)); back.Value = images[0]; armChgBg.KeyFrames.Add(back); } Storyboard.SetTargetName(armChgBg, _window.Beauty.Name); DependencyProperty[] propertyChain2 = new DependencyProperty[] { Canvas.BackgroundProperty, ImageBrush.ImageSourceProperty }; Storyboard.SetTargetProperty(armChgBg, new PropertyPath("(0).(1)", propertyChain2)); return(armChgBg); }
public void CreateMove(double startTime, Button btn, int idx) { var xy = this.xy[idx]; var image = new ImageBrush(); image.ImageSource = new BitmapImage(new Uri("Img/card/back.bmp", UriKind.Relative)); btn.Background = image; #region 控制牌显示 var chgVisible = new ObjectAnimationUsingKeyFrames(); DiscreteObjectKeyFrame dk1 = new DiscreteObjectKeyFrame() { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = Visibility.Hidden }; DiscreteObjectKeyFrame dk2 = new DiscreteObjectKeyFrame() { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startTime)), Value = Visibility.Visible }; DiscreteObjectKeyFrame dk3 = new DiscreteObjectKeyFrame() { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(visibleDuration)), Value = Visibility.Hidden }; chgVisible.KeyFrames.Add(dk1); chgVisible.KeyFrames.Add(dk2); chgVisible.KeyFrames.Add(dk3); Storyboard.SetTargetName(chgVisible, btn.Name); Storyboard.SetTargetProperty(chgVisible, new PropertyPath(Control.VisibilityProperty)); #endregion #region 控制大小 var chgWidth = new DoubleAnimationUsingKeyFrames(); LinearDoubleKeyFrame widthk1 = new LinearDoubleKeyFrame() { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = 0 }; LinearDoubleKeyFrame widthk2 = new LinearDoubleKeyFrame() { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startTime + 0.2)), Value = 99 }; //LinearDoubleKeyFrame widthk3 = new LinearDoubleKeyFrame() //{ // KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(visibleDuration)), // Value = 0 //}; chgWidth.KeyFrames.Add(widthk1); chgWidth.KeyFrames.Add(widthk2); //chgWidth.KeyFrames.Add(widthk3); Storyboard.SetTargetName(chgWidth, btn.Name); Storyboard.SetTargetProperty(chgWidth, new PropertyPath(Button.WidthProperty)); var chgHeight = new DoubleAnimationUsingKeyFrames(); LinearDoubleKeyFrame heightk1 = new LinearDoubleKeyFrame() { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = 0 }; LinearDoubleKeyFrame heightk2 = new LinearDoubleKeyFrame() { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startTime + 0.2)), Value = 132 }; //LinearDoubleKeyFrame heightk3 = new LinearDoubleKeyFrame() //{ // KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(visibleDuration)), // Value = 0 //}; chgHeight.KeyFrames.Add(heightk1); chgHeight.KeyFrames.Add(heightk2); //chgHeight.KeyFrames.Add(widthk3); Storyboard.SetTargetName(chgHeight, btn.Name); Storyboard.SetTargetProperty(chgHeight, new PropertyPath(Button.HeightProperty)); #endregion #region 控制移动 var chgY = new DoubleAnimationUsingKeyFrames(); var y0 = new EasingDoubleKeyFrame() { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = xy[0] }; var yStart = new EasingDoubleKeyFrame() { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startTime)), Value = xy[0] }; var yEnd = new EasingDoubleKeyFrame() { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startTime + move_time)), Value = xy[1] }; chgY.KeyFrames.Add(y0); chgY.KeyFrames.Add(yStart); chgY.KeyFrames.Add(yEnd); Storyboard.SetTargetName(chgY, btn.Name); Storyboard.SetTargetProperty(chgY, new PropertyPath(Canvas.TopProperty)); var chgX = new DoubleAnimationUsingKeyFrames(); var x0 = new EasingDoubleKeyFrame() { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = xy[2] }; var xStart = new EasingDoubleKeyFrame() { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startTime)), Value = xy[2] }; var xEnd = new EasingDoubleKeyFrame() { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startTime + move_time)), Value = xy[3] }; chgX.KeyFrames.Add(x0); chgX.KeyFrames.Add(xStart); chgX.KeyFrames.Add(xEnd); Storyboard.SetTargetName(chgX, btn.Name); Storyboard.SetTargetProperty(chgX, new PropertyPath(Canvas.LeftProperty)); #endregion moveSB.Children.Add(chgWidth); moveSB.Children.Add(chgHeight); moveSB.Children.Add(chgVisible); moveSB.Children.Add(chgY); moveSB.Children.Add(chgX); }
public static ObjectAnimationUsingKeyFrames CreateFrames(GifBitmapDecoder decoder) { if (decoder == null) { return(null); } ObjectAnimationUsingKeyFrames animation = new ObjectAnimationUsingKeyFrames(); // Read MetaData from GIF // this give us the Width and Height of the GIF GifMetaData gifData = GifMetaDataReader.GetGifMetaData(decoder); if (gifData == null) { return(null); } TimeSpan animationTime = TimeSpan.FromMilliseconds(0); BitmapSource baseFrame = null; // create a animation for every frame in GIF foreach (BitmapFrame curFrame in decoder.Frames) { // first we need to read the metadata from the frame // to know the position, width, height, delay and disposalmethod GifFrameMetaData frameMetaData = GifMetaDataReader.GetGifFrameMetaData(curFrame); if (frameMetaData != null) { // Create a "image" from the current frame BitmapSource CurCreatedFrame = GifImageFrameCreator.CreateFrame( new System.Drawing.Size(gifData.Width, gifData.Height), curFrame, frameMetaData, baseFrame); // add the frame to the animaton animation.KeyFrames.Add(new DiscreteObjectKeyFrame() { KeyTime = animationTime, Value = CurCreatedFrame }); // Check the disposal method switch (frameMetaData.DisposalMethod) { case GifFrameDisposalMethod.None: break; case GifFrameDisposalMethod.DoNotDispose: baseFrame = CurCreatedFrame; break; case GifFrameDisposalMethod.RestoreBackground: baseFrame = GifImageFrameCreator.RestoreBackground(new System.Drawing.Size(gifData.Width, gifData.Height), curFrame, frameMetaData); break; case GifFrameDisposalMethod.RestorePrevious: break; default: break; } // increse the timeline with the delay of the frame animationTime += frameMetaData.Delay; } } animation.Duration = animationTime; return(animation); }
public void StartMoving() { storyboard = new Storyboard(); storyboard.SpeedRatio = 2; DoubleAnimationUsingKeyFrames animX = new DoubleAnimationUsingKeyFrames(); animX.Duration = TimeSpan.FromSeconds(PointsToPath.Count); DoubleAnimationUsingKeyFrames animY = new DoubleAnimationUsingKeyFrames(); animY.Duration = TimeSpan.FromSeconds(PointsToPath.Count); for (int i = 0; i < PointsToPath.Count; i++) { var ease = new ExponentialEase(); ease.EasingMode = EasingMode.EaseIn; var kx = new EasingDoubleKeyFrame(); kx.Value = PointsToPath[i].X; kx.KeyTime = TimeSpan.FromSeconds(i); kx.EasingFunction = ease; animX.KeyFrames.Add(kx); var ky = new EasingDoubleKeyFrame(); ky.Value = PointsToPath[i].Y; ky.KeyTime = TimeSpan.FromSeconds(i); ky.EasingFunction = ease; animY.KeyFrames.Add(ky); } var ChangeToPedestrianAnimation = new ObjectAnimationUsingKeyFrames(); for (int i = 0; i < IsPedestrian.Count; i++) { if (IsPedestrian[i]) { var f = new DiscreteObjectKeyFrame(); f.KeyTime = TimeSpan.FromSeconds(i); f.Value = Visibility.Visible; ChangeToPedestrianAnimation.KeyFrames.Add(f); f = new DiscreteObjectKeyFrame(); f.KeyTime = TimeSpan.FromSeconds(i + 1); f.Value = Visibility.Collapsed; ChangeToPedestrianAnimation.KeyFrames.Add(f); } } Storyboard.SetTarget(ChangeToPedestrianAnimation, PedestrianImage); Storyboard.SetTargetProperty(ChangeToPedestrianAnimation, new PropertyPath("Visibility")); Storyboard.SetTargetProperty(animX, new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)")); Storyboard.SetTarget(animX, this); Storyboard.SetTargetProperty(animY, new PropertyPath("(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)")); Storyboard.SetTarget(animY, this); storyboard.Children.Add(animX); storyboard.Children.Add(animY); storyboard.Children.Add(ChangeToPedestrianAnimation); PointsToPath.Clear(); storyboard.Begin(); }
public ValueSetterAnimation(FrameworkElement target, String property) { ObjectAnimation = new ObjectAnimationUsingKeyFrames(); Storyboard.SetTarget(ObjectAnimation, target); Storyboard.SetTargetProperty(ObjectAnimation, property); }
private void StartEdgeAnimation(bool open) { if (!open) { SetBottomAppBarVisibility(Visibility.Visible); } var sb = new Storyboard(); // left offset var to = open ? -CharmWidth : -(CharmWidth * 2) - 1; if (EdgePlacement == HorizontalAlignment.Right) { to = open ? -CharmWidth : 0; } var aTranslate = new DoubleAnimation { EasingFunction = new CircleEase { EasingMode = EasingMode.EaseOut }, From = (_leftMenu.RenderTransform as TranslateTransform).X, To = to, Duration = TimeSpan.FromMilliseconds(200), EnableDependentAnimation = true }; Storyboard.SetTarget(aTranslate, _leftMenu); Storyboard.SetTargetProperty(aTranslate, "(UIElement.RenderTransform).(TranslateTransform.X)"); sb.Children.Add(aTranslate); // opacity var aOpacity = new DoubleAnimation { EasingFunction = new CircleEase { EasingMode = EasingMode.EaseOut }, From = ParentContentElement.Opacity, To = open ? 0.6 : 1, Duration = TimeSpan.FromMilliseconds(200), EnableDependentAnimation = true }; Storyboard.SetTarget(aOpacity, ParentContentElement); Storyboard.SetTargetProperty(aOpacity, "Opacity"); sb.Children.Add(aOpacity); // visibility if (!open) { var aVisibility = new ObjectAnimationUsingKeyFrames(); aVisibility.KeyFrames.Add(new DiscreteObjectKeyFrame { KeyTime = TimeSpan.FromMilliseconds(200), Value = false }); Storyboard.SetTarget(aVisibility, _leftMenu); Storyboard.SetTargetProperty(aVisibility, "IsOpen"); sb.Children.Add(aVisibility); } // depth offset var trans = ParentContentElement.RenderTransform as CompositeTransform; if (trans != null) { var aScaleX = new DoubleAnimation { EasingFunction = new CircleEase { EasingMode = EasingMode.EaseOut }, From = trans.ScaleX, To = open ? 0.92 : 1.0, Duration = TimeSpan.FromMilliseconds(200), EnableDependentAnimation = true }; Storyboard.SetTarget(aScaleX, ParentContentElement); Storyboard.SetTargetProperty(aScaleX, "(UIElement.RenderTransform).(CompositeTransform.ScaleX)"); sb.Children.Add(aScaleX); var aScaleY = new DoubleAnimation { EasingFunction = new CircleEase { EasingMode = EasingMode.EaseOut }, From = trans.ScaleY, To = open ? 0.92 : 1.0, Duration = TimeSpan.FromMilliseconds(200), EnableDependentAnimation = true }; Storyboard.SetTarget(aScaleY, ParentContentElement); Storyboard.SetTargetProperty(aScaleY, "(UIElement.RenderTransform).(CompositeTransform.ScaleY)"); sb.Children.Add(aScaleY); } if (!open) { sb.Completed += sb_Completed; } sb.Begin(); }
private static void InitAnimationOrImage(Image imageControl) { BitmapSource source = GetAnimatedSource(imageControl) as BitmapSource; bool isInDesignMode = DesignerProperties.GetIsInDesignMode(imageControl); bool animateInDesignMode = GetAnimateInDesignMode(imageControl); bool shouldAnimate = !isInDesignMode || animateInDesignMode; // For a BitmapImage with a relative UriSource, the loading is deferred until // BaseUri is set. This method will be called again when BaseUri is set. bool isLoadingDeferred = IsLoadingDeferred(source); if (source != null && shouldAnimate && !isLoadingDeferred) { GifFile gifMetadata; var decoder = GetDecoder(source, out gifMetadata) as GifBitmapDecoder; if (decoder != null && decoder.Frames.Count > 1) { int index = 0; var animation = new ObjectAnimationUsingKeyFrames(); var totalDuration = TimeSpan.Zero; BitmapSource baseFrame = null; foreach (var rawFrame in decoder.Frames) { var metadata = GetFrameMetadata(decoder, gifMetadata, index); var frame = MakeFrame(source, rawFrame, metadata, baseFrame); var keyFrame = new DiscreteObjectKeyFrame(frame, totalDuration); animation.KeyFrames.Add(keyFrame); totalDuration += metadata.Delay; switch (metadata.DisposalMethod) { case FrameDisposalMethod.None: case FrameDisposalMethod.DoNotDispose: baseFrame = frame; break; case FrameDisposalMethod.RestoreBackground: baseFrame = null; break; case FrameDisposalMethod.RestorePrevious: // Reuse same base frame break; } index++; } animation.Duration = totalDuration; animation.RepeatBehavior = GetActualRepeatBehavior(imageControl, decoder, gifMetadata); animation.Completed += delegate { imageControl.RaiseEvent( new RoutedEventArgs(AnimationCompletedEvent, imageControl)); }; animation.Freeze(); if (animation.KeyFrames.Count > 0) { // For some reason, it sometimes throws an exception the first time... the second time it works. TryTwice(() => imageControl.Source = (ImageSource)animation.KeyFrames[0].Value); } else { imageControl.Source = decoder.Frames[0]; } imageControl.BeginAnimation(Image.SourceProperty, animation); return; } } imageControl.Source = source; }
public static void AddAnimation(ImageSource source, RepeatBehavior repeatBehavior, ObjectAnimationUsingKeyFrames animation) { var key = new CacheKey(source, repeatBehavior); AnimationCacheDic[key] = animation; }
/// <summary> /// Sets the property /// </summary> /// <param name="parameter">Unused.</param> protected override void Invoke(object parameter) { if (!string.IsNullOrEmpty(this.PropertyName) && (this.Target != null)) { Type c = this.Target.GetType(); PropertyInfo property = c.GetProperty(this.PropertyName); if (property == null) { throw new ArgumentException("Cannot find property " + this.PropertyName + " on object " + this.Target.GetType().Name); } if (!property.CanWrite) { throw new ArgumentException("Property is read-only " + this.PropertyName + " on object " + this.Target.GetType().Name); } object toValue = this.Value; TypeConverter typeConverter = ConverterHelper.GetTypeConverter(property.PropertyType); Exception innerException = null; try { if (((typeConverter != null) && (this.Value != null)) && typeConverter.CanConvertFrom(this.Value.GetType())) { toValue = typeConverter.ConvertFrom(this.Value); } object fromValue = property.GetValue(this.Target, null); if (this.Increment) { toValue = SetProperty.Add(toValue, fromValue); } if (this.Duration.HasTimeSpan) { Timeline timeline; if ((typeof(FrameworkElement).IsAssignableFrom(c) && ((this.PropertyName == "Width") || (this.PropertyName == "Height"))) && double.IsNaN((double)fromValue)) { FrameworkElement target = (FrameworkElement)this.Target; if (this.PropertyName == "Width") { fromValue = target.ActualWidth; } else { fromValue = target.ActualHeight; } } Storyboard storyboard = new Storyboard(); if (typeof(double).IsAssignableFrom(property.PropertyType)) { DoubleAnimation animation = new DoubleAnimation(); animation.From = new double?((double)fromValue); animation.To = new double?((double)toValue); #if SILVERLIGHT animation.EasingFunction = this.Ease; #endif timeline = animation; } else if (typeof(Color).IsAssignableFrom(property.PropertyType)) { ColorAnimation animation2 = new ColorAnimation(); animation2.From = new Color?((Color)fromValue); animation2.To = new Color?((Color)toValue); #if SILVERLIGHT animation2.EasingFunction = this.Ease; #endif timeline = animation2; } else if (typeof(Point).IsAssignableFrom(property.PropertyType)) { PointAnimation animation3 = new PointAnimation(); animation3.From = new Point?((Point)fromValue); animation3.To = new Point?((Point)toValue); #if SILVERLIGHT animation3.EasingFunction = this.Ease; #endif timeline = animation3; } else { ObjectAnimationUsingKeyFrames frames = new ObjectAnimationUsingKeyFrames(); DiscreteObjectKeyFrame frame = new DiscreteObjectKeyFrame(); frame.KeyTime = KeyTime.FromTimeSpan(new TimeSpan(0L)); frame.Value = fromValue; DiscreteObjectKeyFrame frame2 = new DiscreteObjectKeyFrame(); frame2.KeyTime = KeyTime.FromTimeSpan(this.Duration.TimeSpan); frame2.Value = toValue; frames.KeyFrames.Add(frame); frames.KeyFrames.Add(frame2); timeline = frames; } timeline.Duration = this.Duration; storyboard.Children.Add(timeline); Storyboard.SetTarget(storyboard, this.Target); Storyboard.SetTargetProperty(storyboard, new PropertyPath(property.Name, new object[0])); storyboard.Begin(); } else { property.SetValue(this.Target, toValue, new object[0]); } } catch (FormatException exception2) { innerException = exception2; } catch (ArgumentException exception3) { innerException = exception3; } catch (MethodAccessException exception4) { innerException = exception4; } if (innerException != null) { throw new ArgumentException(innerException.Message); } } }
/// <summary> /// Uses ObjectAnimatioNUsingKeyFrames and a StoryBoard to animated to expansion /// of the specificed ColumnDefinition or RowDefinition. /// </summary> /// <param name="definition">The RowDefinition or ColumnDefintition that will be expanded.</param> private void AnimateExpand(object definition) { double increment; double currentValue; // Setup the animation and StoryBoard ObjectAnimationUsingKeyFrames gridLengthAnimation = new ObjectAnimationUsingKeyFrames(); Storyboard sb = new Storyboard(); // Add the animation to the StoryBoard sb.Children.Add(gridLengthAnimation); if (_gridCollapseDirection == GridCollapseDirection.Rows) { // Specify the target RowDefinition and property (Height) that will be altered by the animation. RowDefinition rowDefinition = (RowDefinition)definition; Storyboard.SetTarget(gridLengthAnimation, rowDefinition); Storyboard.SetTargetProperty(gridLengthAnimation, new PropertyPath("Height")); increment = _savedActualValue / 5; currentValue = rowDefinition.ActualHeight; } else { // Specify the target ColumnDefinition and property (Width) that will be altered by the animation. ColumnDefinition colDefinition = (ColumnDefinition)definition; Storyboard.SetTarget(gridLengthAnimation, colDefinition); Storyboard.SetTargetProperty(gridLengthAnimation, new PropertyPath("Width")); increment = _savedActualValue / 5; currentValue = colDefinition.ActualWidth; } // Create frames to incrementally expand the target. DiscreteObjectKeyFrame keyFrame1 = new DiscreteObjectKeyFrame(); keyFrame1.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(.1)); currentValue = currentValue + increment; keyFrame1.Value = new GridLength(currentValue); gridLengthAnimation.KeyFrames.Add(keyFrame1); DiscreteObjectKeyFrame keyFrame2 = new DiscreteObjectKeyFrame(); keyFrame2.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(.2)); currentValue = currentValue + increment; keyFrame2.Value = new GridLength(currentValue); gridLengthAnimation.KeyFrames.Add(keyFrame2); DiscreteObjectKeyFrame keyFrame3 = new DiscreteObjectKeyFrame(); keyFrame3.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(.3)); currentValue = currentValue + increment; keyFrame3.Value = new GridLength(currentValue); gridLengthAnimation.KeyFrames.Add(keyFrame3); DiscreteObjectKeyFrame keyFrame4 = new DiscreteObjectKeyFrame(); keyFrame4.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(.4)); currentValue = currentValue + increment; keyFrame4.Value = new GridLength(currentValue); gridLengthAnimation.KeyFrames.Add(keyFrame4); DiscreteObjectKeyFrame keyFrame5 = new DiscreteObjectKeyFrame(); keyFrame5.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(.5)); keyFrame5.Value = _savedGridLength; gridLengthAnimation.KeyFrames.Add(keyFrame5); // Start the StoryBoard. sb.Begin(); }
private static void InitAnimationOrImage(Image imageControl) { var controller = GetAnimationController(imageControl); if (controller != null) { controller.Dispose(); } SetAnimationController(imageControl, null); SetIsAnimationLoaded(imageControl, false); BitmapSource source = GetAnimatedSource(imageControl) as BitmapSource; bool isInDesignMode = DesignerProperties.GetIsInDesignMode(imageControl); bool animateInDesignMode = GetAnimateInDesignMode(imageControl); bool shouldAnimate = !isInDesignMode || animateInDesignMode; // For a BitmapImage with a relative UriSource, the loading is deferred until // BaseUri is set. This method will be called again when BaseUri is set. bool isLoadingDeferred = IsLoadingDeferred(source); if (source != null && shouldAnimate && !isLoadingDeferred) { // Case of image being downloaded: retry after download is complete if (source.IsDownloading) { void handler(object sender, EventArgs args) { source.DownloadCompleted -= handler; InitAnimationOrImage(imageControl); } source.DownloadCompleted += handler; imageControl.Source = source; return; } ObjectAnimationUsingKeyFrames animation = GetAnimation(imageControl, source); if (animation != null) { if (animation.KeyFrames.Count > 0) { // For some reason, it sometimes throws an exception the first time... the second time it works. TryTwice(() => imageControl.Source = (ImageSource)animation.KeyFrames[0].Value); } else { imageControl.Source = source; } controller = new ImageAnimationController(imageControl, animation, GetAutoStart(imageControl)); SetAnimationController(imageControl, controller); SetIsAnimationLoaded(imageControl, true); imageControl.RaiseEvent(new RoutedEventArgs(AnimationLoadedEvent, imageControl)); return; } } imageControl.Source = source; if (source != null) { SetIsAnimationLoaded(imageControl, true); imageControl.RaiseEvent(new RoutedEventArgs(AnimationLoadedEvent, imageControl)); } }
public static void StartContinuumForwardOutAnimation(FrameworkElement tapedItem, FrameworkElement tapedItemContainer) { _lastTapedItem = tapedItem; _lastTapedItem.CacheMode = new BitmapCache(); var storyboard = new Storyboard(); var timeline = new DoubleAnimationUsingKeyFrames(); timeline.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = TimeSpan.FromSeconds(0.0), Value = 0.0 }); timeline.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = TimeSpan.FromSeconds(0.25), Value = 73.0 }); Storyboard.SetTarget(timeline, tapedItem); Storyboard.SetTargetProperty(timeline, new PropertyPath("(UIElement.RenderTransform).(CompositeTransform.TranslateY)")); storyboard.Children.Add(timeline); var timeline2 = new DoubleAnimationUsingKeyFrames(); timeline2.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = TimeSpan.FromSeconds(0.0), Value = 0.0 }); timeline2.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = TimeSpan.FromSeconds(0.25), Value = 425.0, EasingFunction = new ExponentialEase { EasingMode = EasingMode.EaseIn, Exponent = 5.0 } }); Storyboard.SetTarget(timeline2, tapedItem); Storyboard.SetTargetProperty(timeline2, new PropertyPath("(UIElement.RenderTransform).(CompositeTransform.TranslateX)")); storyboard.Children.Add(timeline2); var timeline3 = new DoubleAnimationUsingKeyFrames(); timeline3.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = TimeSpan.FromSeconds(0.0), Value = 1.0 }); timeline3.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = TimeSpan.FromSeconds(0.2), Value = 1.0 }); timeline3.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = TimeSpan.FromSeconds(0.25), Value = 0.0 }); Storyboard.SetTarget(timeline3, tapedItem); Storyboard.SetTargetProperty(timeline3, new PropertyPath("(UIElement.Opacity)")); storyboard.Children.Add(timeline3); if (tapedItemContainer != null) { var timeline4 = new ObjectAnimationUsingKeyFrames(); timeline4.KeyFrames.Add(new DiscreteObjectKeyFrame { KeyTime = TimeSpan.FromSeconds(0.0), Value = 999.0 }); timeline4.KeyFrames.Add(new DiscreteObjectKeyFrame { KeyTime = TimeSpan.FromSeconds(0.25), Value = 0.0 }); Storyboard.SetTarget(timeline4, tapedItemContainer); Storyboard.SetTargetProperty(timeline4, new PropertyPath("(Canvas.ZIndex)")); storyboard.Children.Add(timeline4); } storyboard.Begin(); }
private void MainItemGrid_OnTap(object sender, GestureEventArgs e) { if (ViewModel.IsWorking) { return; } var frameworkElement = sender as FrameworkElement; if (frameworkElement == null) { return; } var user = frameworkElement.DataContext as TLUserBase; if (user == null) { return; } ViewModel.UserAction(user); var tapedItem = frameworkElement; _tapedItem = tapedItem; VisualTreeExtensions.FindVisualChildWithPredicate <TextBlock>(tapedItem, AnimatedBasePage.GetIsAnimationTarget); if (!(_tapedItem.RenderTransform is CompositeTransform)) { _tapedItem.RenderTransform = new CompositeTransform(); } FrameworkElement tapedItemContainer = _tapedItem.FindParentOfType <ListBoxItem>(); if (tapedItemContainer != null) { tapedItemContainer = tapedItemContainer.FindParentOfType <ContentPresenter>(); } var storyboard = new Storyboard(); var timeline = new DoubleAnimationUsingKeyFrames(); timeline.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = TimeSpan.FromSeconds(0.0), Value = 0.0 }); timeline.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = TimeSpan.FromSeconds(0.25), Value = 73.0 }); Storyboard.SetTarget(timeline, tapedItem); Storyboard.SetTargetProperty(timeline, new PropertyPath("(UIElement.RenderTransform).(CompositeTransform.TranslateY)")); storyboard.Children.Add(timeline); var timeline2 = new DoubleAnimationUsingKeyFrames(); timeline2.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = TimeSpan.FromSeconds(0.0), Value = 0.0 }); timeline2.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = TimeSpan.FromSeconds(0.25), Value = 425.0, EasingFunction = new ExponentialEase { EasingMode = EasingMode.EaseIn, Exponent = 5.0 } }); Storyboard.SetTarget(timeline2, tapedItem); Storyboard.SetTargetProperty(timeline2, new PropertyPath("(UIElement.RenderTransform).(CompositeTransform.TranslateX)")); storyboard.Children.Add(timeline2); var timeline3 = new DoubleAnimationUsingKeyFrames(); timeline3.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = TimeSpan.FromSeconds(0.0), Value = 1.0 }); timeline3.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = TimeSpan.FromSeconds(0.2), Value = 1.0 }); timeline3.KeyFrames.Add(new EasingDoubleKeyFrame { KeyTime = TimeSpan.FromSeconds(0.25), Value = 0.0 }); Storyboard.SetTarget(timeline3, tapedItem); Storyboard.SetTargetProperty(timeline3, new PropertyPath("(UIElement.Opacity)")); storyboard.Children.Add(timeline3); if (tapedItemContainer != null) { var timeline4 = new ObjectAnimationUsingKeyFrames(); timeline4.KeyFrames.Add(new DiscreteObjectKeyFrame { KeyTime = TimeSpan.FromSeconds(0.0), Value = 999.0 }); timeline4.KeyFrames.Add(new DiscreteObjectKeyFrame { KeyTime = TimeSpan.FromSeconds(0.25), Value = 0.0 }); Storyboard.SetTarget(timeline4, tapedItemContainer); Storyboard.SetTargetProperty(timeline4, new PropertyPath("(Canvas.ZIndex)")); storyboard.Children.Add(timeline4); } _lastStoryboard = storyboard; storyboard.Begin(); }
private void Flash() { Storyboard storyBoard = new Storyboard(); MainCanvas.Children.Clear(); MainCanvas.Background = ColorHelper.GetBrushFromString(_message.BackgroundColor); Grid g = new Grid(); g.Width = 800; g.Height = 480; g.ColumnDefinitions.Add(new ColumnDefinition()); g.RowDefinitions.Add(new RowDefinition()); MainCanvas.Children.Add(g); string text = _message.Text; string[] words = text.Split(' '); for (var i = 0; i <= words.Length - 1; i++) { TextBlock tb = getTextBlock(); tb.Text = words[i]; tb.FontSize = getFontSize(); tb.Foreground = ColorHelper.GetBrushFromString(_message.ForegroundColor); while (tb.ActualWidth > 800) { tb.FontSize -= 1; System.Diagnostics.Debug.WriteLine("FontSize: " + tb.FontSize); } tb.VerticalAlignment = System.Windows.VerticalAlignment.Center; tb.HorizontalAlignment = System.Windows.HorizontalAlignment.Center; tb.Visibility = System.Windows.Visibility.Collapsed; g.Children.Add(tb); double seconds = ((MAX_SPEED - _message.Speed) + 1) * SPEED_INTERVAL; double startingTime = ((i * 2) + 1) * seconds; ObjectAnimationUsingKeyFrames animation = new ObjectAnimationUsingKeyFrames(); DiscreteObjectKeyFrame visibleKeyFrame = new DiscreteObjectKeyFrame(); visibleKeyFrame.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startingTime)); visibleKeyFrame.Value = Visibility.Visible; animation.KeyFrames.Add(visibleKeyFrame); DiscreteObjectKeyFrame collapsedKeyFrame = new DiscreteObjectKeyFrame(); collapsedKeyFrame.KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(startingTime + seconds)); collapsedKeyFrame.Value = Visibility.Collapsed; animation.KeyFrames.Add(collapsedKeyFrame); Storyboard.SetTarget(animation, tb); Storyboard.SetTargetProperty(animation, new PropertyPath("(UIElement.Visibility)")); storyBoard.Children.Add(animation); } if (storyBoard.Children.Count > 0) { storyBoard.RepeatBehavior = RepeatBehavior.Forever; storyBoard.Begin(); } }
internal MultiplyFrameImageExDisplaySource(ImageExSource source, RepeatBehavior repeatBehavior) { if (source == null) { throw new ArgumentNullException(nameof(source)); } _frames = source.Frames; if (_frames == null || _frames.Length <= 1) { throw new ArgumentException("This source is a single frame source."); } Width = source.Width; Height = source.Height; _animationFrameBridge = new AnimationBridge <SKBitmap>(); _animationFrameBridge.ValueChanged += AnimationFrameBridge_ValueChanged; var storyboard = new Storyboard(); var animation = new ObjectAnimationUsingKeyFrames(); if (repeatBehavior == default) { var repetitionCount = source.RepetitionCount; if (repetitionCount == -1) { animation.RepeatBehavior = RepeatBehavior.Forever; } else if (repetitionCount > 0) { animation.RepeatBehavior = new RepeatBehavior(repetitionCount); } } else { animation.RepeatBehavior = repeatBehavior; } var frameCount = _frames.Length; var totalDuration = 0; for (var frameIndex = 0; frameIndex < frameCount; frameIndex++) { var frame = _frames[frameIndex]; var bitmap = frame.Bitmap; var duration = frame.Duration; animation.KeyFrames.Add(new DiscreteObjectKeyFrame { Value = bitmap, KeyTime = TimeSpan.FromMilliseconds(totalDuration) }); totalDuration += duration; } animation.Duration = TimeSpan.FromMilliseconds(totalDuration); Storyboard.SetTarget(animation, _animationFrameBridge); Storyboard.SetTargetProperty(animation, new PropertyPath(nameof(_animationFrameBridge.Value))); storyboard.Children.Add(animation); _animation = animation; _storyboard = storyboard; }
private static ObjectAnimationUsingKeyFrames GetAnimation(Image imageControl, BitmapSource source) { var cacheEntry = AnimationCache.Get(source); if (cacheEntry == null) { var decoder = GetDecoder(source, imageControl, out GifFile gifMetadata) as GifBitmapDecoder; if (decoder != null && decoder.Frames.Count > 1) { var fullSize = GetFullSize(decoder, gifMetadata); int index = 0; var keyFrames = new ObjectKeyFrameCollection(); var totalDuration = TimeSpan.Zero; BitmapSource baseFrame = null; foreach (var rawFrame in decoder.Frames) { var metadata = GetFrameMetadata(decoder, gifMetadata, index); var frame = MakeFrame(fullSize, rawFrame, metadata, baseFrame); var keyFrame = new DiscreteObjectKeyFrame(frame, totalDuration); keyFrames.Add(keyFrame); totalDuration += metadata.Delay; switch (metadata.DisposalMethod) { case FrameDisposalMethod.None: case FrameDisposalMethod.DoNotDispose: baseFrame = frame; break; case FrameDisposalMethod.RestoreBackground: if (IsFullFrame(metadata, fullSize)) { baseFrame = null; } else { baseFrame = ClearArea(frame, metadata); } break; case FrameDisposalMethod.RestorePrevious: // Reuse same base frame break; } index++; } int repeatCount = GetRepeatCountFromMetadata(decoder, gifMetadata); cacheEntry = new AnimationCacheEntry(keyFrames, totalDuration, repeatCount); AnimationCache.Add(source, cacheEntry); } } if (cacheEntry != null) { var animation = new ObjectAnimationUsingKeyFrames { KeyFrames = cacheEntry.KeyFrames, Duration = cacheEntry.Duration, RepeatBehavior = GetActualRepeatBehavior(imageControl, cacheEntry.RepeatCountFromMetadata), SpeedRatio = GetActualSpeedRatio(imageControl, cacheEntry.Duration) }; AnimationCache.AddControlForSource(source, imageControl); return(animation); } return(null); }
public static Storyboard GetShow(AirspacePanel tbMarkdownPanel, Grid gridNote, Rectangle gridSplitterMarkdown) { // Fixes the first time width to half the screen tbMarkdownPanel.Width = gridNote.ActualWidth / 2; tbMarkdownPanel.Margin = new Thickness(0, 0, -tbMarkdownPanel.Width, 0); var visAnim = new ObjectAnimationUsingKeyFrames() { Duration = new Duration(TimeSpan.FromMilliseconds(500)), KeyFrames = new ObjectKeyFrameCollection() { new DiscreteObjectKeyFrame(Visibility.Visible, KeyTime.FromPercent(1)) } }; Storyboard.SetTarget(visAnim, gridSplitterMarkdown); Storyboard.SetTargetProperty(visAnim, new PropertyPath("(FrameworkElement.Visibility)")); var marginAnim = new ThicknessAnimationUsingKeyFrames() { Duration = new Duration(TimeSpan.FromMilliseconds(500)), KeyFrames = new ThicknessKeyFrameCollection() { new EasingThicknessKeyFrame(new Thickness(0), KeyTime.FromPercent(1)) { EasingFunction = new SineEase() { EasingMode = EasingMode.EaseOut } } } }; Storyboard.SetTarget(marginAnim, tbMarkdownPanel); Storyboard.SetTargetProperty(marginAnim, new PropertyPath("(FrameworkElement.Margin)")); var widthAnim = new DoubleAnimationUsingKeyFrames() { Duration = new Duration(TimeSpan.FromMilliseconds(500)), KeyFrames = new DoubleKeyFrameCollection() { new SplineDoubleKeyFrame(tbMarkdownPanel.ActualWidth, KeyTime.FromPercent(0.999)), new SplineDoubleKeyFrame(Double.NaN, KeyTime.FromPercent(1)) } }; Storyboard.SetTarget(marginAnim, tbMarkdownPanel); Storyboard.SetTargetProperty(marginAnim, new PropertyPath("(FrameworkElement.Margin)")); var sb = new Storyboard() { Children = new TimelineCollection() { visAnim, marginAnim } }; sb.Completed += (sender, args) => { tbMarkdownPanel.Width = gridNote.ActualWidth / 2; tbMarkdownPanel.Margin = new Thickness(0, 0, 0, 0); }; return(sb); }
/// <summary> /// Dock the MainWindow based on its location. /// </summary> /// <param name="changePos">Update LastDockStatus if set to True.</param> internal void DockToSide(bool changePos = false) { if (DockedTo == DockStatus.None) { double toval; DependencyProperty tgtpro; double pad = 15d; DockStatus dockto; if (changePos) { App.CurrScrnRect = new GetCurrentMonitor().GetInfo(this); if (Left <= App.CurrScrnRect.Left) //dock left { toval = App.CurrScrnRect.Left - ActualWidth + pad; tgtpro = LeftProperty; dockto = DockStatus.Left; } else if (Left + ActualWidth >= App.CurrScrnRect.Right) //dock right { toval = App.CurrScrnRect.Right - pad; tgtpro = LeftProperty; dockto = DockStatus.Right; } else if (Top <= App.CurrScrnRect.Top) //dock top { toval = App.CurrScrnRect.Top - ActualHeight + pad; tgtpro = TopProperty; dockto = DockStatus.Top; } else if (Top + ActualHeight >= App.CurrScrnRect.Bottom) //dock bottom { toval = App.CurrScrnRect.Bottom - pad; tgtpro = TopProperty; dockto = DockStatus.Bottom; } else { LastDockStatus = DockStatus.None; return; } LastDockStatus = dockto; } else //'restore last docking position { dockto = LastDockStatus; switch (LastDockStatus) { case DockStatus.Left: toval = App.CurrScrnRect.Left - ActualWidth + pad; tgtpro = LeftProperty; break; case DockStatus.Right: toval = App.CurrScrnRect.Right - pad; tgtpro = LeftProperty; break; case DockStatus.Top: toval = App.CurrScrnRect.Top - ActualHeight + pad; tgtpro = TopProperty; break; case DockStatus.Bottom: toval = App.CurrScrnRect.Bottom - pad; tgtpro = TopProperty; break; default: return; } } var anim_move = new DoubleAnimation(toval, new Duration(new TimeSpan(0, 0, 0, 0, 500))) { EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut } }; var anim_fade = new DoubleAnimation(0.4, new Duration(new TimeSpan(0, 0, 0, 0, 300))) { BeginTime = new TimeSpan(0, 0, 0, 0, 200) }; var anim_prop = new ObjectAnimationUsingKeyFrames(); anim_prop.KeyFrames.Add(new DiscreteObjectKeyFrame(DockStatus.Docking, KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0)))); anim_prop.KeyFrames.Add(new DiscreteObjectKeyFrame(dockto, KeyTime.FromTimeSpan(new TimeSpan(0, 0, 0, 0, 500)))); BeginAnimation(tgtpro, anim_move); BeginAnimation(OpacityProperty, anim_fade); BeginAnimation(DockedToProperty, anim_prop); } }
public static ObjectAnimationUsingKeyFrames AddDiscreteObjectKeyFrame(this ObjectAnimationUsingKeyFrames objectAnimation, double seconds, object value) { objectAnimation.AddDiscreteObjectKeyFrame(TimeSpan.FromSeconds(seconds), value); return(objectAnimation); }
private static Storyboard CreateStoryboard( FrameworkElement target, DependencyProperty animatingDependencyProperty, string propertyPath, ref object toValue, TimeSpan durationTimeSpan, EasingFunctionBase easingFunction) { object fromValue = target.GetValue(animatingDependencyProperty); double fromDoubleValue; double toDoubleValue; DateTime fromDateTime; DateTime toDateTime; Storyboard storyBoard = new Storyboard(); Storyboard.SetTarget(storyBoard, target); Storyboard.SetTargetProperty(storyBoard, propertyPath); if ((fromValue != null && toValue != null)) { if (ValueHelper.TryConvert(fromValue, out fromDoubleValue) && ValueHelper.TryConvert(toValue, out toDoubleValue)) { DoubleAnimation doubleAnimation = new DoubleAnimation(); doubleAnimation.EnableDependentAnimation = true; #if !NO_EASING_FUNCTIONS doubleAnimation.EasingFunction = easingFunction; #endif doubleAnimation.Duration = durationTimeSpan; doubleAnimation.To = ValueHelper.ToDouble(toValue); toValue = doubleAnimation.To; storyBoard.Children.Add(doubleAnimation); } else if (ValueHelper.TryConvert(fromValue, out fromDateTime) && ValueHelper.TryConvert(toValue, out toDateTime)) { ObjectAnimationUsingKeyFrames keyFrameAnimation = new ObjectAnimationUsingKeyFrames(); keyFrameAnimation.EnableDependentAnimation = true; keyFrameAnimation.Duration = durationTimeSpan; long intervals = (long)(durationTimeSpan.TotalSeconds * KeyFramesPerSecond); if (intervals < 2L) { intervals = 2L; } IEnumerable <TimeSpan> timeSpanIntervals = ValueHelper.GetTimeSpanIntervalsInclusive(durationTimeSpan, intervals); IEnumerable <DateTime> dateTimeIntervals = ValueHelper.GetDateTimesBetweenInclusive(fromDateTime, toDateTime, intervals); IEnumerable <DiscreteObjectKeyFrame> keyFrames = EnumerableFunctions.Zip( dateTimeIntervals, timeSpanIntervals, (dateTime, timeSpan) => new DiscreteObjectKeyFrame() { Value = dateTime, KeyTime = timeSpan }); foreach (DiscreteObjectKeyFrame keyFrame in keyFrames) { keyFrameAnimation.KeyFrames.Add(keyFrame); toValue = keyFrame.Value; } storyBoard.Children.Add(keyFrameAnimation); } } if (storyBoard.Children.Count == 0) { ObjectAnimationUsingKeyFrames keyFrameAnimation = new ObjectAnimationUsingKeyFrames(); keyFrameAnimation.EnableDependentAnimation = true; DiscreteObjectKeyFrame endFrame = new DiscreteObjectKeyFrame() { Value = toValue, KeyTime = new TimeSpan(0, 0, 0) }; keyFrameAnimation.KeyFrames.Add(endFrame); storyBoard.Children.Add(keyFrameAnimation); } return(storyBoard); }
private static Storyboard CreateStoryboard(this DependencyObject target, DependencyProperty animatingDependencyProperty, string propertyPath, string propertyKey, ref object toValue, TimeSpan durationTimeSpan, IEasingFunction easingFunction) { object obj = target.GetValue(animatingDependencyProperty); Storyboard storyboard = new Storyboard(); Storyboard.SetTarget((DependencyObject)storyboard, target); Storyboard.SetTargetProperty((DependencyObject)storyboard, new PropertyPath(propertyPath, new object[0])); if (obj != null && toValue != null) { double doubleValue1; double doubleValue2; if (ValueHelper.TryConvert(obj, out doubleValue1) && ValueHelper.TryConvert(toValue, out doubleValue2)) { DoubleAnimation doubleAnimation = new DoubleAnimation(); doubleAnimation.Duration = (Duration)durationTimeSpan; doubleAnimation.To = new double?(ValueHelper.ToDouble(toValue)); toValue = (object)doubleAnimation.To; storyboard.Children.Add((Timeline)doubleAnimation); } else { DateTime dateTimeValue1; DateTime dateTimeValue2; if (ValueHelper.TryConvert(obj, out dateTimeValue1) && ValueHelper.TryConvert(toValue, out dateTimeValue2)) { ObjectAnimationUsingKeyFrames animationUsingKeyFrames = new ObjectAnimationUsingKeyFrames(); animationUsingKeyFrames.Duration = (Duration)durationTimeSpan; long count = (long)(durationTimeSpan.TotalSeconds * 20.0); if (count < 2L) { count = 2L; } IEnumerable <TimeSpan> intervalsInclusive = ValueHelper.GetTimeSpanIntervalsInclusive(durationTimeSpan, count); foreach (DiscreteObjectKeyFrame discreteObjectKeyFrame in Enumerable.Zip <DateTime, TimeSpan, DiscreteObjectKeyFrame>(ValueHelper.GetDateTimesBetweenInclusive(dateTimeValue1, dateTimeValue2, count), intervalsInclusive, (Func <DateTime, TimeSpan, DiscreteObjectKeyFrame>)((dateTime, timeSpan) => { return(new DiscreteObjectKeyFrame() { Value = (object)dateTime, KeyTime = (KeyTime)timeSpan }); }))) { animationUsingKeyFrames.KeyFrames.Add((ObjectKeyFrame)discreteObjectKeyFrame); toValue = discreteObjectKeyFrame.Value; } storyboard.Children.Add((Timeline)animationUsingKeyFrames); } } } if (storyboard.Children.Count == 0) { ObjectAnimationUsingKeyFrames animationUsingKeyFrames = new ObjectAnimationUsingKeyFrames(); DiscreteObjectKeyFrame discreteObjectKeyFrame1 = new DiscreteObjectKeyFrame(); discreteObjectKeyFrame1.Value = toValue; discreteObjectKeyFrame1.KeyTime = (KeyTime) new TimeSpan(0, 0, 0); DiscreteObjectKeyFrame discreteObjectKeyFrame2 = discreteObjectKeyFrame1; animationUsingKeyFrames.KeyFrames.Add((ObjectKeyFrame)discreteObjectKeyFrame2); storyboard.Children.Add((Timeline)animationUsingKeyFrames); } return(storyboard); }