private void Add(string text, int code) { base.Dispatcher.Invoke(() => { if (!string.IsNullOrEmpty(text)) { TextBlock textBlock = new TextBlock(); logPanel.Children.Add(textBlock); logCount++; textBlock.Name = "text" + logCount.ToString(); if (!atAnimation) { atAnimation = true; double EndY; TextBlock prev = logPanel.Children[0] as TextBlock; if (prev.ActualHeight != double.NaN) { if (prev.ActualHeight < 20) { EndY = -(logCount * prev.ActualHeight / 1.0f - logScrollView.ActualHeight); } else { EndY = -(logCount * prev.ActualHeight / 4.0f - logScrollView.ActualHeight); } } else { EndY = -logCount * 15; } DoubleAnimation AnimationY = new DoubleAnimation(saveY, EndY, TimeSpan.FromSeconds(1)); AnimationY.Completed += AnimationY_Completed; saveY = EndY; TranslateTransform Transform = new TranslateTransform(); logPanel.RenderTransform = Transform; Transform.BeginAnimation(TranslateTransform.YProperty, AnimationY); } ColorAnimation animation = new ColorAnimation { Duration = new Duration(TimeSpan.FromSeconds(10)) }; switch (code) { case 0: animation.To = ((SolidColorBrush)App.Current.Resources["OWLOSSuccessAlpha4"]).Color; textBlock.Foreground = new SolidColorBrush(((SolidColorBrush)App.Current.Resources["OWLOSSuccess"]).Color); break; case 1: animation.To = ((SolidColorBrush)App.Current.Resources["OWLOSWarningAlpha4"]).Color; textBlock.Foreground = new SolidColorBrush(((SolidColorBrush)App.Current.Resources["OWLOSWarning"]).Color); break; case 3: animation.To = ((SolidColorBrush)App.Current.Resources["OWLOSDangerAlpha4"]).Color; textBlock.Foreground = new SolidColorBrush(((SolidColorBrush)App.Current.Resources["OWLOSDanger"]).Color); break; default: animation.To = ((SolidColorBrush)App.Current.Resources["OWLOSInfoAlpha4"]).Color; textBlock.Foreground = new SolidColorBrush(((SolidColorBrush)App.Current.Resources["OWLOSLight"]).Color); break; } textBlock.Foreground.BeginAnimation(SolidColorBrush.ColorProperty, animation); //https://stackoverflow.com/questions/3430659/is-there-a-wpf-typewriter-effect Storyboard story = new Storyboard { FillBehavior = FillBehavior.HoldEnd }; StringAnimationUsingKeyFrames stringAnimationUsingKeyFrames = new StringAnimationUsingKeyFrames { Duration = new Duration(TimeSpan.FromSeconds(1)) }; string tempText = string.Empty; text = DateTime.Now + " " + text; foreach (char c in text) { DiscreteStringKeyFrame discreteStringKeyFrame = new DiscreteStringKeyFrame { KeyTime = KeyTime.Paced }; tempText += c; stringAnimationUsingKeyFrames.KeyFrames.Add(discreteStringKeyFrame); if (tempText.Length < text.Length) { discreteStringKeyFrame.Value = tempText + "█"; } else { discreteStringKeyFrame.Value = tempText; } } Storyboard.SetTargetProperty(stringAnimationUsingKeyFrames, new PropertyPath(TextBlock.TextProperty)); story.Children.Add(stringAnimationUsingKeyFrames); story.Begin(textBlock); } }); }
/// <summary> /// Overrides the standard ArrangeOverride method from the <see cref="System.Windows.FrameworkElement" /> class. /// </summary> /// <param name="finalSize">The final area within the parent that this element should use to arrange itself and its children.</param> /// <returns> /// The actual size used. /// </returns> protected override Size ArrangeOverride(Size finalSize) { // If an item was removed don't move resp. animate anything if (removedUIElement != null) { return(finalSize); } // If a row was added and as a result of this the panel height has changed don't move resp. animate anything if (changeOfPanelHeightInProgress) { changeOfPanelHeightInProgress = false; return(finalSize); } // Set the time stamp at the beginning of the arrangement process var startArrangementTimeStamp = DateTime.Now.Ticks; // Iterate through all childs in the UIElementCollection for (var i = 0; i < Children.Count; i++) { // Get the current child by it's index var child = Children[i]; if (child == null) { continue; } // Try to find the current child in our internal child collection var existingChild = internalChildCollection.FirstOrDefault(item => item.Child.Equals(child)); if (existingChild == null) { // If the current child is not in our internal child collection, then add it to our internal collection internalChildCollection.Add(new UIElementWithMetaData { Child = child, ChildIndex = i, IsRecentlyAdded = true }); } else { existingChild.IsRecentlyAdded = false; } } // Calculate the width and height of every single Slot var slotWidth = finalSize.Width / ColumnCount; var slotHeight = finalSize.Height / RowCount; // Calculate the initial horizontal and vertical offset var horizontalOffset = slotWidth * (ColumnCount - 1); // ReSharper disable once PossibleLossOfFraction var verticalOffset = slotHeight * (internalChildCollection.Count / ColumnCount); // Determine if the first column is full var isFirstColumnFull = (internalChildCollection.Count % ColumnCount).Equals(0); // This is our column counter var currentColumn = ColumnCount; // Here we hold all indexes of childs which are involved in the merge process var currentRowMergeIndexes = new List <int>(); var previousRowMergeIndexes = new List <int>(); // Count of row pairs to merge ( 2 rows -> 1 row ) var countOfRowPairs = 0; // Count of deleted childs in curent row pair, so we can skip all childs after ColumnColunt childs were removed var countOfDeletedChildsInCurrentRowPair = 0; // If a new child was added and the first column is full ... if (newChildAdded && isFirstColumnFull) { // ... iterate through all rows for (var i = 0; i < internalChildCollection.Count; i += ColumnCount) { var removedChildsInCurrentRow = 0; var removedChildsInPreviousRow = 0; // Determine the first and last child indexes of the current and previous row var firstChildIndexInCurrentRow = i - (i % ColumnCount); var lastChildIndexInCurrentRow = firstChildIndexInCurrentRow + ColumnCount - 1; var firstChildIndexInPreviousRow = firstChildIndexInCurrentRow + ColumnCount; var lastChildIndexInPreviousRow = lastChildIndexInCurrentRow + ColumnCount; // Count all removed childs in the current row for (var childIndex = firstChildIndexInCurrentRow; childIndex <= lastChildIndexInCurrentRow; childIndex++) { if (childIndex >= internalChildCollection.Count) { continue; } if (internalChildCollection[childIndex].IsRemoved) { removedChildsInCurrentRow++; } } // Count all removed childs in the previous row for (var childIndex = firstChildIndexInPreviousRow; childIndex <= lastChildIndexInPreviousRow; childIndex++) { if (childIndex >= internalChildCollection.Count) { continue; } if (internalChildCollection[childIndex].IsRemoved) { removedChildsInPreviousRow++; } } // If all removed childs in the current row and the previous row are greater or equal to the column count ... if (removedChildsInCurrentRow + removedChildsInPreviousRow >= ColumnCount) { // ... add all child indexes of the current and previous row to our index lists currentRowMergeIndexes.AddRange(Enumerable.Range(firstChildIndexInCurrentRow, ColumnCount)); previousRowMergeIndexes.AddRange(Enumerable.Range(firstChildIndexInPreviousRow, ColumnCount)); countOfRowPairs++; i += ColumnCount; } } // Update the initial vertical offset considering the count of row pairs if (countOfRowPairs > 0) { verticalOffset -= slotHeight * countOfRowPairs; } } // Iterate through all childs in our internal child collection for (var i = 0; i < internalChildCollection.Count; i++) { // Get the current internal child by it's index var existingChild = internalChildCollection[i]; var child = existingChild.Child; if (child == null) { continue; } // Get the current TransformGroup var existingTransformGroup = child.RenderTransform as TransformGroup; var translateTransform = new TranslateTransform(); var skewTransform = new SkewTransform(); var transformGroup = new TransformGroup(); // If there is no current TransformGroup, create a new one ... if (existingTransformGroup == null) { transformGroup.Children.Add(translateTransform); transformGroup.Children.Add(skewTransform); child.RenderTransform = transformGroup; } else { // ... else retrieve the available Transform objects from the existing TransformGroup translateTransform = existingTransformGroup.Children[0] as TranslateTransform; skewTransform = existingTransformGroup.Children[1] as SkewTransform; } // First arrangement of the child on position [0,0] with the size of a single Slot // The animation values will overwrite this first position settings child.Arrange(new Rect(0, 0, slotWidth, slotHeight)); // New childs will slide in from outside ... var fromHorizontalPosition = -slotWidth; var fromVerticalPosition = 0.0; // If the current child wasn't recently added and the initial size change is not in progress ... if (!internalChildCollection[i].IsRecentlyAdded && !initialSizeChangeInProgress) { // ... retrieve the current position as the animation start position fromHorizontalPosition = existingChild.CurrentPosition.X; fromVerticalPosition = existingChild.CurrentPosition.Y; } // Update the current position data and the animation progress state existingChild.CurrentPosition = new Point(horizontalOffset, verticalOffset); existingChild.HorizontalAnimationInProgress = true; var mergeInProgress = false; var lastChildIndexInCurrentRow = -1; if (translateTransform != null) { // Animate the vertical position of the current child from the childs current vertical position // to the calculated vertical offset var verticalAnimation = new DoubleAnimation(fromVerticalPosition, verticalOffset, MovementAnimationDuration) { AccelerationRatio = 0.5, DecelerationRatio = 0.3 }; // If the first column is full ... if (newChildAdded && isFirstColumnFull) { // ... merge corresponding rows, where the cumulated item count is equal to the column count var removedChildsInCurrentRow = 0; // var removedChildsInNextRow = 0; // Determine the first and last child indexes of the current and next row var firstChildIndexInCurrentRow = i - (i % ColumnCount); lastChildIndexInCurrentRow = firstChildIndexInCurrentRow + ColumnCount - 1; // var firstChildIndexInNextRow = firstChildIndexInCurrentRow - ColumnCount; // var lastChildIndexInNextRow = lastChildIndexInCurrentRow - ColumnCount; // Count all removed childs in the current row for (var childIndex = firstChildIndexInCurrentRow; childIndex <= lastChildIndexInCurrentRow; childIndex++) { if (childIndex >= internalChildCollection.Count) { continue; } if (internalChildCollection[childIndex].IsRemoved) { removedChildsInCurrentRow++; } } // Count all removed childs in the next row // for (var childIndex = firstChildIndexInNextRow; childIndex <= lastChildIndexInNextRow; childIndex++) // { // if (childIndex < 0 || childIndex >= internalChildCollection.Count) continue; // if (internalChildCollection[childIndex].IsRemoved) removedChildsInNextRow++; // } // If the current child is located in a row to merge if (currentRowMergeIndexes.Contains(i) || previousRowMergeIndexes.Contains(i)) { mergeInProgress = true; // If the child is marked as removed ... if (existingChild.IsRemoved) { // ... update the horizontal offset horizontalOffset += slotWidth; // ... and mark the child for deletion // (only if all deleted childs in the current row pair don't exceed the ColumnCount) if (++countOfDeletedChildsInCurrentRowPair <= ColumnCount) { existingChild.IsMarkedForDeletion = true; } } // If the child is the first child in the previous row ... if (previousRowMergeIndexes.Contains(i) && i == firstChildIndexInCurrentRow) { // ... update the horizontal offset horizontalOffset -= slotWidth * removedChildsInCurrentRow; // horizontalOffset -= slotWidth * (ColumnCount - removedChildsInPreviousRow); } } else { lastChildIndexInCurrentRow = -1; countOfDeletedChildsInCurrentRowPair = 0; } // Start the movement of all lines AFTER the sliding movement and the arrangement is finished verticalAnimation.BeginTime = MovementAnimationDuration.TimeSpan + arrangementTimeSpan; // If there are rows to merge .. if (countOfRowPairs > 0) { // ... add the merge animation delay to the vertical animation delay verticalAnimation.BeginTime += MergeAnimationDelay.TimeSpan; } } // Hook the vertical animation completed event, so we can remove the childs which are marked for deletion verticalAnimation.Completed += (os, ea) => verticalAnimation_Completed(child); // Apply the vertical animation ONLY if the vertical position has changed if (!fromVerticalPosition.Equals(verticalOffset)) { // !----------------------------------------------------------------------------------------------------------------- Debug.WriteLine("Vertical Movement Item No. {0} from {1} to {2} ", i, fromVerticalPosition, verticalOffset); // !----------------------------------------------------------------------------------------------------------------- translateTransform.BeginAnimation(TranslateTransform.YProperty, verticalAnimation, HandoffBehavior.Compose); } // Animate the horizontal position of the current child from the childs current horizontal position // to the calculated horizontal offset var horizontalAnimation = new DoubleAnimation(fromHorizontalPosition, horizontalOffset, MovementAnimationDuration) { AccelerationRatio = 0.5, DecelerationRatio = 0.3 }; // Hook the animation completed event, so we can change the "HorizontalAnimationInProgress" flag horizontalAnimation.Completed += (os, ea) => horizontalAnimation_Completed(child); if (internalChildCollection[i].IsRecentlyAdded || existingChild.HorizontalAnimationInProgress == false || resizeInProgress || mergeInProgress) { // !----------------------------------------------------------------------------------------------------------------- Debug.WriteLine("Horizontal Movement Item No. " + i); Debug.WriteLine("Arrange time span : " + arrangementTimeSpan.TotalMilliseconds); // !----------------------------------------------------------------------------------------------------------------- // Set the beginning of the horizontal animation to the end of the arrangement process // (this will prevent unpredictable animation effects) horizontalAnimation.BeginTime = arrangementTimeSpan; // If a merge is in progress.. if (mergeInProgress) { // ... add the merge animation delay to the horizontal animation horizontalAnimation.BeginTime += MergeAnimationDelay.TimeSpan; // If we have the last child of the current merged row reset the horizontal offset to EPSILON if (currentRowMergeIndexes.Contains(i) && i == lastChildIndexInCurrentRow) { horizontalOffset = EPSILON; } } else { // This is neccessary to move the child to it's current horizontal start position var moveToStartPositionAnimation = new DoubleAnimation(fromHorizontalPosition, fromHorizontalPosition, new Duration(new TimeSpan(0))); translateTransform.BeginAnimation(TranslateTransform.XProperty, moveToStartPositionAnimation, HandoffBehavior.Compose); } translateTransform.BeginAnimation(TranslateTransform.XProperty, horizontalAnimation, HandoffBehavior.Compose); } } existingChild.CurrentPosition = new Point(horizontalOffset, verticalOffset); //// If the child is the last child in the current merged row ... // if (currentRowMergeIndexes.Contains( i ) && i == lastChildIndexInCurrentRow) // // ... update the vertical offset // verticalOffset += slotHeight; // If the current child is the first in the row, then update the vertical and horizontal offset for the next childs // and set the current column to the last column in the row if (horizontalOffset <= EPSILON) { // If the child is not the last child in a row that is currently merged ... if (!(currentRowMergeIndexes.Contains(i) && i == lastChildIndexInCurrentRow)) { verticalOffset -= slotHeight; // ... update the vertical offset for the next child } horizontalOffset = slotWidth * (ColumnCount - 1); // Update the horizontal offset for the next child currentColumn = ColumnCount; // Reset our column counter to last column in row } else { // If we have the recently added child ... if (newChildAdded && child.Equals(addedUIElement) && skewTransform != null) { // ... perform an additional skew animation // Calculate the skew angle dependent on the distance to the end of line (base angle = -30°) var skewAngle = -30.0 * ((double)currentColumn / ColumnCount); var skewAnimation = new DoubleAnimationUsingKeyFrames { Duration = MovementAnimationDuration, BeginTime = arrangementTimeSpan }; var fractionOfMovementAnimationDuration = (MovementAnimationDuration.TimeSpan.Multiply(0.65)); skewAnimation.KeyFrames.Add(new LinearDoubleKeyFrame(skewAngle, // Target value (KeyValue) KeyTime.FromTimeSpan(fractionOfMovementAnimationDuration)) // KeyTime ); skewAnimation.KeyFrames.Add(new LinearDoubleKeyFrame(0, // Target value (KeyValue) KeyTime.FromTimeSpan(MovementAnimationDuration.TimeSpan)) // KeyTime ); skewTransform.BeginAnimation(SkewTransform.AngleXProperty, skewAnimation, HandoffBehavior.Compose); newChildAdded = false; } horizontalOffset -= slotWidth; // Update the horizontal offset for the next child currentColumn--; // Increase our column counter } } // Set the time stamp at the end of the arrangement process var endArrangementTimeStamp = DateTime.Now.Ticks; // Calculate the time span of the arrangement process arrangementTimeSpan = new TimeSpan(endArrangementTimeStamp - startArrangementTimeStamp); // Calculate the required rows (with respect to the count of childs marked for deletion) var countOfChildsMarkedForDeletion = internalChildCollection.Count(item => item.IsMarkedForDeletion); // (Centigrade IW) not used because the calculation is wrong, when the panel is resized to fullscreen var requiredRows = (internalChildCollection.Count - countOfChildsMarkedForDeletion) / ColumnCount + 1; //If we need more rows ... if (requiredRows > RowCount) { // ... increase the RowCount ... RowCount += requiredRows - RowCount; // ... and adjust the height of the panel itself this.Height = requiredRows * slotHeight; changeOfPanelHeightInProgress = true; } // Fill all the space given return(finalSize); }
#pragma warning restore SA1201 // Elements should appear in the correct order private Drawing GetBouldersDrawing() { Duration duration = new Duration(new TimeSpan(0, 0, 0, 0, this.moveTime)); var ggg = new DrawingGroup(); foreach (var d in this.model.Boulders) { if (d != null) { TranslateTransform boulderTranslate = new TranslateTransform(d.TilePosition.X * this.TileSize, d.TilePosition.Y * this.TileSize); DoubleAnimation animX = new DoubleAnimation(d.TileOldPosition.X * this.TileSize, d.TilePosition.X * this.TileSize, duration); DoubleAnimation animY = new DoubleAnimation(d.TileOldPosition.Y * this.TileSize, d.TilePosition.Y * this.TileSize, duration); animX.EasingFunction = new PowerEase() { EasingMode = EasingMode.EaseInOut, Power = 1.2 }; animY.EasingFunction = new PowerEase() { EasingMode = EasingMode.EaseInOut, Power = 1.2 }; boulderTranslate.BeginAnimation(TranslateTransform.XProperty, animX); boulderTranslate.BeginAnimation(TranslateTransform.YProperty, animY); Geometry boulder = new RectangleGeometry(new Rect(0, 0, this.TileSize, this.TileSize)); boulder.Transform = boulderTranslate; if (this.model.Camera.IsInStage(d.TilePosition)) { ImageBrush brush; if (!this.boulderBrushCache.ContainsKey(d)) { Brush tmpBrush; switch (d.Variant) { case 1: tmpBrush = this.assetBrushes[nameof(Properties.Resources.Boulder1)].Clone(); break; case 2: tmpBrush = this.assetBrushes[nameof(Properties.Resources.Boulder2)].Clone(); break; case 3: tmpBrush = this.assetBrushes[nameof(Properties.Resources.Boulder3)].Clone(); break; case 4: tmpBrush = this.assetBrushes[nameof(Properties.Resources.Boulder4)].Clone(); break; default: throw new Exception("Unknown boulder set"); } this.boulderBrushCache[d] = tmpBrush; brush = tmpBrush as ImageBrush; } else { brush = this.boulderBrushCache[d] as ImageBrush; } brush.TileMode = TileMode.None; brush.Viewport = new Rect(0, 0, this.TileSize, this.TileSize); brush.ViewportUnits = BrushMappingMode.Absolute; brush.Transform = boulderTranslate; d.TileOldPosition = d.TilePosition; ggg.Children.Add(new GeometryDrawing(brush, null, boulder)); } } } return(ggg); }
private void clicked(object sender, RoutedEventArgs e) { if (_toggled) { DoubleAnimation db = new DoubleAnimation(); if (InitialValue) { db.From = 0; db.To = -_deltaX; } else { db.From = _deltaX; db.To = 0; } db.Duration = new Duration(TimeSpan.FromSeconds(0.5)); TranslateTransform tt = new TranslateTransform(); toggleEllipse.RenderTransform = tt; tt.BeginAnimation(TranslateTransform.XProperty, db); ColorAnimation color = new ColorAnimation(); color.From = this.OnColor; color.To = this.OffColor; innerCircle.Fill = new SolidColorBrush((Color)color.From); color.Duration = new Duration(TimeSpan.FromSeconds(0.5)); innerCircle.Fill.BeginAnimation(SolidColorBrush.ColorProperty, color); textDetail.Text = this.OffText; } else { DoubleAnimation db = new DoubleAnimation(); if (InitialValue) { db.From = -_deltaX; db.To = 0; } else { db.From = 0; db.To = _deltaX; } db.Duration = new Duration(TimeSpan.FromSeconds(0.5)); TranslateTransform tt = new TranslateTransform(); toggleEllipse.RenderTransform = tt; tt.BeginAnimation(TranslateTransform.XProperty, db); ColorAnimation color = new ColorAnimation(); color.From = this.OffColor; color.To = this.OnColor; innerCircle.Fill = new SolidColorBrush((Color)color.From); color.Duration = new Duration(TimeSpan.FromSeconds(0.5)); innerCircle.Fill.BeginAnimation(SolidColorBrush.ColorProperty, color); textDetail.Text = this.OnText; } _toggled = !_toggled; IsToggled = _toggled; }
private void createKeyTimePacedExample() { // <SnippetKeyTimesPacedExample> /* * This rectangle is animated with KeyTimes using Paced Values. * The rectangle moves between key frames at uniform rate except for first key frame * because using a Paced value on the first KeyFrame in a collection of frames gives a time of zero. */ // Create the a rectangle. Rectangle aRectangle = new Rectangle(); aRectangle.Fill = Brushes.Orange; aRectangle.Stroke = Brushes.Black; aRectangle.StrokeThickness = 5; aRectangle.Width = 50; aRectangle.Height = 50; // Create a transform to move the rectangle // across the screen. TranslateTransform translateTransform4 = new TranslateTransform(); aRectangle.RenderTransform = translateTransform4; // Create a DoubleAnimationUsingKeyFrames // to animate the transform. DoubleAnimationUsingKeyFrames transformAnimation = new DoubleAnimationUsingKeyFrames(); transformAnimation.Duration = TimeSpan.FromSeconds(10); /* * Use Paced values when a constant rate is desired. * The time allocated to a key frame with a KeyTime of "Paced" is * determined by the time allocated to the other key frames of the animation. This time is * calculated to attempt to give a "paced" or "constant velocity" for the animation. */ // Animate to 100. transformAnimation.KeyFrames.Add( new LinearDoubleKeyFrame(100, KeyTime.Paced)); // Animate to 300. transformAnimation.KeyFrames.Add( new LinearDoubleKeyFrame(300, KeyTime.Paced)); // Animate to 500. transformAnimation.KeyFrames.Add( new LinearDoubleKeyFrame(500, KeyTime.Paced)); // Start the animation when the rectangle is loaded. aRectangle.Loaded += delegate(object sender, RoutedEventArgs e) { translateTransform4.BeginAnimation(TranslateTransform.XProperty, transformAnimation); }; // </SnippetKeyTimesPacedExample> mainPanel.Children.Add(aRectangle); }
#pragma warning restore SA1201 // Elements should appear in the correct order private Drawing GetDiamondsDrawing() { Duration duration = new Duration(new TimeSpan(0, 0, 0, 0, this.moveTime)); var ggg = new DrawingGroup(); foreach (var d in this.model.Diamonds) { if (d != null) { TranslateTransform diamondTranslate = new TranslateTransform(d.TilePosition.X * this.TileSize, d.TilePosition.Y * this.TileSize); if (!d.TilePosition.Equals(d.TileOldPosition) && this.model.Camera.IsInStage(d.TilePosition)) { DoubleAnimation animX = new DoubleAnimation(d.TileOldPosition.X * this.TileSize, d.TilePosition.X * this.TileSize, duration); DoubleAnimation animY = new DoubleAnimation(d.TileOldPosition.Y * this.TileSize, d.TilePosition.Y * this.TileSize, duration); animX.EasingFunction = new PowerEase() { EasingMode = EasingMode.EaseInOut, Power = 1.2 }; animY.EasingFunction = new PowerEase() { EasingMode = EasingMode.EaseInOut, Power = 1.2 }; diamondTranslate.BeginAnimation(TranslateTransform.XProperty, animX); diamondTranslate.BeginAnimation(TranslateTransform.YProperty, animY); } Geometry dia = new RectangleGeometry(new Rect(0, 0, this.TileSize, this.TileSize)); dia.Transform = diamondTranslate; d.TileOldPosition = d.TilePosition; if (this.model.Camera.IsInStage(d.TilePosition)) { if (this.visualBrushCache.ContainsKey(d)) { var brush = this.visualBrushCache[d]; // brush.TileMode = TileMode.None; // brush.Viewport = new Rect(0, 0, TileSize, TileSize); // brush.ViewportUnits = BrushMappingMode.Absolute; brush.Transform = diamondTranslate; if (brush.CanFreeze) { brush.Freeze(); } ggg.Children.Add(new GeometryDrawing(brush, null, dia)); } else { var brush = this.animatedVisualBrushes["Diamond" + this.model.TextureSet].Clone(); RenderOptions.SetCachingHint(brush, CachingHint.Cache); this.visualBrushCache[d] = brush; brush.TileMode = TileMode.None; brush.Viewport = new Rect(0, 0, this.TileSize, this.TileSize); brush.ViewportUnits = BrushMappingMode.Absolute; brush.Transform = diamondTranslate; ggg.Children.Add(new GeometryDrawing(brush, null, dia)); } } } } return(ggg); }
public void Wipe(TransitionerSlide fromSlide, TransitionerSlide toSlide, Point origin, IZIndexController zIndexController) { if (fromSlide == null) { throw new ArgumentNullException(nameof(fromSlide)); } if (toSlide == null) { throw new ArgumentNullException(nameof(toSlide)); } if (zIndexController == null) { throw new ArgumentNullException(nameof(zIndexController)); } // Set up time points var zeroKeyTime = KeyTime.FromTimeSpan(TimeSpan.Zero); var endKeyTime = KeyTime.FromTimeSpan(Duration); // Set up coordinates double fromStartX = 0, fromEndX = 0, toStartX = 0, toEndX = 0; double fromStartY = 0, fromEndY = 0, toStartY = 0, toEndY = 0; if (Direction == SlideDirection.Left) { fromEndX = -fromSlide.ActualWidth; toStartX = toSlide.ActualWidth; } else if (Direction == SlideDirection.Right) { fromEndX = fromSlide.ActualWidth; toStartX = -toSlide.ActualWidth; } else if (Direction == SlideDirection.Up) { fromEndY = -fromSlide.ActualHeight; toStartY = toSlide.ActualHeight; } else if (Direction == SlideDirection.Down) { fromEndY = fromSlide.ActualHeight; toStartY = -toSlide.ActualHeight; } // From var fromTransform = new TranslateTransform(fromStartX, fromStartY); fromSlide.RenderTransform = fromTransform; var fromXAnimation = new DoubleAnimationUsingKeyFrames(); fromXAnimation.KeyFrames.Add(new LinearDoubleKeyFrame(fromStartX, zeroKeyTime)); fromXAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(fromEndX, endKeyTime, _sineEase)); var fromYAnimation = new DoubleAnimationUsingKeyFrames(); fromYAnimation.KeyFrames.Add(new LinearDoubleKeyFrame(fromStartY, zeroKeyTime)); fromYAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(fromEndY, endKeyTime, _sineEase)); // To var toTransform = new TranslateTransform(toStartX, toStartY); toSlide.RenderTransform = toTransform; var toXAnimation = new DoubleAnimationUsingKeyFrames(); toXAnimation.KeyFrames.Add(new LinearDoubleKeyFrame(toStartX, zeroKeyTime)); toXAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(toEndX, endKeyTime, _sineEase)); var toYAnimation = new DoubleAnimationUsingKeyFrames(); toYAnimation.KeyFrames.Add(new LinearDoubleKeyFrame(toStartY, zeroKeyTime)); toYAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(toEndY, endKeyTime, _sineEase)); // Set up events fromXAnimation.Completed += (sender, args) => { fromTransform.BeginAnimation(TranslateTransform.XProperty, null); fromTransform.X = fromEndX; fromSlide.RenderTransform = null; }; fromYAnimation.Completed += (sender, args) => { fromTransform.BeginAnimation(TranslateTransform.YProperty, null); fromTransform.Y = fromEndY; fromSlide.RenderTransform = null; }; toXAnimation.Completed += (sender, args) => { toTransform.BeginAnimation(TranslateTransform.XProperty, null); toTransform.X = toEndX; toSlide.RenderTransform = null; }; toYAnimation.Completed += (sender, args) => { toTransform.BeginAnimation(TranslateTransform.YProperty, null); toTransform.Y = toEndY; toSlide.RenderTransform = null; }; // Animate fromTransform.BeginAnimation(TranslateTransform.XProperty, fromXAnimation); fromTransform.BeginAnimation(TranslateTransform.YProperty, fromYAnimation); toTransform.BeginAnimation(TranslateTransform.XProperty, toXAnimation); toTransform.BeginAnimation(TranslateTransform.YProperty, toYAnimation); zIndexController.Stack(toSlide, fromSlide); }
/// <summary> /// Creates the brush for the ProgressBar /// </summary> /// <param name="values">ForegroundBrush, IsIndeterminate, Width, Height</param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns>Brush for the ProgressBar</returns> public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { // // Parameter Validation // Type doubleType = typeof(double); if (values == null || (values.Length != 3) || (values[0] == null) || (values[1] == null) || (values[2] == null) || !typeof(Brush).IsAssignableFrom(values[0].GetType()) || !doubleType.IsAssignableFrom(values[1].GetType()) || !doubleType.IsAssignableFrom(values[2].GetType())) { return(null); } // // Conversion // Brush brush = (Brush)values[0]; double width = (double)values[1]; double height = (double)values[2]; // if an invalid height, return a null brush if (width <= 0.0 || Double.IsInfinity(width) || Double.IsNaN(width) || height <= 0.0 || Double.IsInfinity(height) || Double.IsNaN(height)) { return(null); } DrawingBrush newBrush = new DrawingBrush(); // Create a Drawing Brush that is 2x longer than progress bar track // // +-------------+.............. // | highlight | empty : // +-------------+.............: // // This brush will animate to the right. double twiceWidth = width * 2.0; // Set the viewport and viewbox to the 2*size of the progress region newBrush.Viewport = newBrush.Viewbox = new Rect(-width, 0, twiceWidth, height); newBrush.ViewportUnits = newBrush.ViewboxUnits = BrushMappingMode.Absolute; newBrush.TileMode = TileMode.None; newBrush.Stretch = Stretch.None; DrawingGroup myDrawing = new DrawingGroup(); DrawingContext myDrawingContext = myDrawing.Open(); // Draw the highlight myDrawingContext.DrawRectangle(brush, null, new Rect(-width, 0, width, height)); // Animate the Translation TimeSpan translateTime = TimeSpan.FromSeconds(twiceWidth / 200.0); // travel at 200px /second TimeSpan pauseTime = TimeSpan.FromSeconds(1.0); // pause 1 second between animations DoubleAnimationUsingKeyFrames animation = new DoubleAnimationUsingKeyFrames(); animation.BeginTime = TimeSpan.Zero; animation.Duration = new Duration(translateTime + pauseTime); animation.RepeatBehavior = RepeatBehavior.Forever; animation.KeyFrames.Add(new LinearDoubleKeyFrame(twiceWidth, translateTime)); TranslateTransform translation = new TranslateTransform(); // Set the animation to the XProperty translation.BeginAnimation(TranslateTransform.XProperty, animation); // Set the animated translation on the brush newBrush.Transform = translation; myDrawingContext.Close(); newBrush.Drawing = myDrawing; return(newBrush); }
public override void Plot(bool animate = true) { var chart = Chart as IStackedBar; if (chart == null) { return; } var stackedSeries = Chart.Series.OfType <StackedBarSeries>().ToList(); var serieIndex = stackedSeries.IndexOf(this); var unitW = ToPlotArea(1, AxisTags.X) - Chart.PlotArea.X + 5; var overflow = unitW - chart.MaxColumnWidth > 0 ? unitW - chart.MaxColumnWidth : 0; unitW = unitW > chart.MaxColumnWidth ? chart.MaxColumnWidth : unitW; var pointPadding = .1 * unitW; const int seriesPadding = 2; var barW = unitW - 2 * pointPadding; for (var index = 0; index < PrimaryValues.Count; index++) { var d = PrimaryValues[index]; var t = new TranslateTransform(); var helper = chart.IndexTotals[index]; var barH = ToPlotArea(Chart.Min.Y, AxisTags.Y) - ToPlotArea(helper.Total, AxisTags.Y); var rh = barH * (d / helper.Total); if (double.IsNaN(rh)) { return; } var stackedH = barH * (helper.Stacked[serieIndex].Stacked / helper.Total); var r = new Rectangle { StrokeThickness = StrokeThickness, Stroke = Stroke, Fill = Fill, Width = Math.Max(0, barW - seriesPadding), Height = 0, RenderTransform = t }; var hr = new Rectangle { StrokeThickness = 0, Fill = Brushes.Transparent, Width = Math.Max(0, barW - seriesPadding), Height = rh }; Canvas.SetLeft(r, ToPlotArea(index, AxisTags.X) + pointPadding + overflow / 2); Canvas.SetLeft(hr, ToPlotArea(index, AxisTags.X) + pointPadding + overflow / 2); Canvas.SetTop(hr, ToPlotArea(Chart.Min.Y, AxisTags.Y) - rh - stackedH); Panel.SetZIndex(hr, int.MaxValue); Chart.Canvas.Children.Add(r); Chart.Canvas.Children.Add(hr); Shapes.Add(r); Shapes.Add(hr); var hAnim = new DoubleAnimation { To = rh, Duration = TimeSpan.FromMilliseconds(300) }; var rAnim = new DoubleAnimation { From = ToPlotArea(Chart.Min.Y, AxisTags.Y), To = ToPlotArea(Chart.Min.Y, AxisTags.Y) - rh - stackedH, Duration = TimeSpan.FromMilliseconds(300) }; var animated = false; if (!Chart.DisableAnimation) { if (animate) { r.BeginAnimation(HeightProperty, hAnim); t.BeginAnimation(TranslateTransform.YProperty, rAnim); animated = true; } } if (!animated) { r.Height = rh; if (rAnim.To != null) { t.Y = (double)rAnim.To; } } if (!Chart.Hoverable) { continue; } hr.MouseEnter += Chart.DataMouseEnter; hr.MouseLeave += Chart.DataMouseLeave; Chart.HoverableShapes.Add(new HoverableShape { Series = this, Shape = hr, Target = r, Value = new Point(index, d) }); } }
public void ghostAnimation(Ghost ghostN) { double left = Canvas.GetLeft(ghostN); double top = Canvas.GetTop(ghostN); // double left = 600; // double top = 300; if (left == double.NaN) { left = 600; } Canvas.SetLeft(this, left); Canvas.SetTop(this, top); // var uriSource = new Uri(@"/PresentationTrainer;component/Images/ic_fb_move_more.png", UriKind.Relative); // ghostMoving.Source = new BitmapImage(uriSource); var animationWidth = new DoubleAnimation(); ghostN.RenderTransformOrigin = new Point(0.5, 0.5); // animationWidth.From = this.animationWidth; animationWidth.From = 300; animationWidth.To = 30; animationWidth.Duration = new Duration(TimeSpan.FromMilliseconds(2000)); Storyboard.SetTarget(animationWidth, this); Storyboard.SetTargetProperty(animationWidth, new PropertyPath(UserControl.WidthProperty)); var animationOpacity = new DoubleAnimation(); animationOpacity.From = 1.0; animationOpacity.To = 0; animationOpacity.Duration = new Duration(TimeSpan.FromMilliseconds(2000)); Storyboard.SetTarget(animationOpacity, this); Storyboard.SetTargetProperty(animationOpacity, new PropertyPath(UIElement.OpacityProperty)); Storyboard animatingGhost = new Storyboard(); // animatingGhost.Children.Add(animationTranslateLeft); // animatingGhost.Children.Add(animationTranslateTop); animatingGhost.Children.Add(animationWidth); animatingGhost.Children.Add(animationOpacity); // animatingGhost.b // animatingGhost.Completed += animatingGhost_Completed; animatingGhost.Begin(); TranslateTransform trans = new TranslateTransform(); this.RenderTransform = trans; DoubleAnimation anim1; try { anim1 = new DoubleAnimation(0, 230 - left, TimeSpan.FromSeconds(1)); } catch { anim1 = new DoubleAnimation(0, 230 - 600, TimeSpan.FromSeconds(1)); } DoubleAnimation anim2 = new DoubleAnimation(0, -255 - top + this.Height / 2, TimeSpan.FromSeconds(1)); trans.BeginAnimation(TranslateTransform.XProperty, anim1); trans.BeginAnimation(TranslateTransform.YProperty, anim2); }
/// <summary> /// item moving animation with all directions /// </summary> /// <param name="item"></param> /// <param name="direction"></param> /// <param name="duration"></param> /// <param name="inOut"></param> private static void FlyAnimation(object item, string direction, double duration, string inOut, int top, int left) { int inValueY = 0; int inValueX = 0; int endValueX = 0; int endValueY = 0; int screenHeight = (int)SystemParameters.PrimaryScreenHeight; int screenWight = Convert.ToInt32(SystemParameters.PrimaryScreenWidth); if (inOut == "in") { inValueY = screenHeight; inValueX = screenWight; endValueX = 0; endValueY = 0; } else if (inOut == "out") { inValueY = 0; inValueX = 0; endValueX = screenWight; endValueY = screenHeight; } DoubleAnimation doubleAnimationX = new DoubleAnimation(); DoubleAnimation doubleAnimationY = new DoubleAnimation(); doubleAnimationX.To = endValueX; doubleAnimationY.To = endValueY; doubleAnimationX.Duration = TimeSpan.FromMilliseconds(duration); doubleAnimationY.Duration = TimeSpan.FromMilliseconds(duration); var trans = new TranslateTransform(); switch (direction) { case "N": if (inOut == "in") { doubleAnimationY.From = (screenHeight - top); } else { doubleAnimationY.From = top; } trans.BeginAnimation(TranslateTransform.YProperty, doubleAnimationY); break; case "NE": if (inOut == "in") { doubleAnimationX.From = (screenWight - left); doubleAnimationY.From = (screenHeight - top); } else { doubleAnimationX.From = left; doubleAnimationY.From = top; } trans.BeginAnimation(TranslateTransform.YProperty, doubleAnimationY); trans.BeginAnimation(TranslateTransform.XProperty, doubleAnimationX); break; case "E": if (inOut == "in") { doubleAnimationX.From = -(screenWight - left); } else { if (left == 0) { doubleAnimationX.From = -left; } else { doubleAnimationX.From = -(screenWight - left); } } trans.BeginAnimation(TranslateTransform.XProperty, doubleAnimationX); break; case "SE": if (inOut == "in") { doubleAnimationX.From = left; doubleAnimationY.From = -(screenHeight - top); } else { doubleAnimationX.From = (screenWight - left); doubleAnimationY.From = -(screenHeight - top); } trans.BeginAnimation(TranslateTransform.YProperty, doubleAnimationY); trans.BeginAnimation(TranslateTransform.XProperty, doubleAnimationX); break; case "S": if (inOut == "in") { doubleAnimationX.From = -(screenHeight - top); } else { doubleAnimationX.From = -top; } trans.BeginAnimation(TranslateTransform.YProperty, doubleAnimationX); break; case "SW": if (inOut == "in") { doubleAnimationX.From = (screenWight - left); doubleAnimationY.From = -top; } else { doubleAnimationX.From = left; doubleAnimationY.From = -(screenHeight - left); } trans.BeginAnimation(TranslateTransform.XProperty, doubleAnimationX); trans.BeginAnimation(TranslateTransform.YProperty, doubleAnimationY); break; case "W": if (inOut == "in") { doubleAnimationX.From = (screenWight - left); } else { doubleAnimationX.From = -left; } trans.BeginAnimation(TranslateTransform.XProperty, doubleAnimationX); break; case "NW": if (inOut == "in") { doubleAnimationX.From = (screenWight - left); doubleAnimationY.From = (screenHeight - top); } else { doubleAnimationX.From = left; doubleAnimationY.From = top; } trans.BeginAnimation(TranslateTransform.XProperty, doubleAnimationX); trans.BeginAnimation(TranslateTransform.YProperty, doubleAnimationY); break; } if (item is System.Windows.Controls.Image) { (item as System.Windows.Controls.Image).RenderTransform = trans; } else if (item is MediaElement) { (item as MediaElement).RenderTransform = trans; } else if (item is ChromiumWebBrowser) { (item as ChromiumWebBrowser).RenderTransform = trans; } }
public Missile(TranslateTransform copterTransform, Duration duration, Grid grid) { _missile = new TextBlock() { Text = asciiMissile, Foreground = new SolidColorBrush(Color.FromRgb(255, 255, 255)), FontFamily = new FontFamily("Courier New"), //Background = new SolidColorBrush(Color.FromRgb(40,40,40)), Width = 180, Height = 70 }; var easingX = new ExponentialEase { EasingMode = EasingMode.EaseInOut, Exponent = 3 }; var easingY = new SineEase { EasingMode = EasingMode.EaseInOut, }; var easingPitch = new QuadraticEase { EasingMode = EasingMode.EaseOut }; var missileTimeSpan = new TimeSpan(0, 0, duration.TimeSpan.Seconds / 2); double width = grid.RenderSize.Width; //_animateX = new DoubleAnimation((width / 2) * -1, (width / 2) + _missile.ActualWidth, new Duration(missileTimeSpan)); _animateX = new DoubleAnimation(copterTransform.X, width * 2, new Duration(missileTimeSpan)) { EasingFunction = easingX }; _animateY = new DoubleAnimation(copterTransform.Y + 100, copterTransform.Y + 200, new Duration(new TimeSpan(0, 0, 1))) { EasingFunction = easingY }; _animatePitch = new DoubleAnimation(0, -5, new Duration(new TimeSpan(0, 0, 1))) { EasingFunction = easingPitch, AutoReverse = true }; _translatePitch = new RotateTransform(0); _translateXY = new TranslateTransform(copterTransform.X, copterTransform.Y); var group = new TransformGroup(); _missile.RenderTransform = group; group.Children.Add(_translatePitch); group.Children.Add(_translateXY); _missile.Loaded += (s, a) => { _animateX.Completed += AnimationCompletedHandler; _translatePitch.BeginAnimation(RotateTransform.AngleProperty, _animatePitch); _translateXY.BeginAnimation(TranslateTransform.XProperty, _animateX); _translateXY.BeginAnimation(TranslateTransform.YProperty, _animateY); #if DEBUG _timer = new Timer(Debugger, copterTransform, 0, 1000); #endif }; _activeGrid = grid; _activeGrid.Children.Add(_missile); }
public void Wipe(TransitionerSlide fromSlide, TransitionerSlide toSlide, Point origin, IZIndexController zIndexController) { if (fromSlide == null) { throw new ArgumentNullException(nameof(fromSlide)); } if (toSlide == null) { throw new ArgumentNullException(nameof(toSlide)); } if (zIndexController == null) { throw new ArgumentNullException(nameof(zIndexController)); } var zeroKeyTime = KeyTime.FromTimeSpan(TimeSpan.Zero); var midishKeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(200)); var endKeyTime = KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(400)); //back out old slide setup var scaleTransform = new ScaleTransform(1, 1); fromSlide.RenderTransform = scaleTransform; var scaleAnimation = new DoubleAnimationUsingKeyFrames(); scaleAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(1, zeroKeyTime)); scaleAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(.8, endKeyTime)); scaleAnimation.Completed += (sender, args) => { fromSlide.RenderTransform = null; }; var opacityAnimation = new DoubleAnimationUsingKeyFrames(); opacityAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(1, zeroKeyTime)); opacityAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(0, endKeyTime)); opacityAnimation.Completed += (sender, args) => { fromSlide.BeginAnimation(UIElement.OpacityProperty, null); fromSlide.Opacity = 0; }; //slide in new slide setup var translateTransform = new TranslateTransform(0, toSlide.ActualHeight); toSlide.RenderTransform = translateTransform; var slideAnimation = new DoubleAnimationUsingKeyFrames(); slideAnimation.KeyFrames.Add(new LinearDoubleKeyFrame(toSlide.ActualHeight, zeroKeyTime)); slideAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(toSlide.ActualHeight, midishKeyTime) { EasingFunction = _sineEase }); slideAnimation.KeyFrames.Add(new EasingDoubleKeyFrame(0, endKeyTime) { EasingFunction = _sineEase }); //kick off! translateTransform.BeginAnimation(TranslateTransform.YProperty, slideAnimation); scaleTransform.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnimation); scaleTransform.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnimation); fromSlide.BeginAnimation(UIElement.OpacityProperty, opacityAnimation); zIndexController.Stack(toSlide, fromSlide); }
/// <summary> /// Creates the brush for the ProgressBar /// </summary> /// <param name="values">ForegroundBrush, IsIndeterminate, Indicator Width, Indicator Height, Track Width</param> /// <param name="targetType"></param> /// <param name="parameter"></param> /// <param name="culture"></param> /// <returns>Brush for the ProgressBar</returns> public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { // // Parameter Validation // Type doubleType = typeof(double); if (values == null || (values.Length != 5) || (values[0] == null) || (values[1] == null) || (values[2] == null) || (values[3] == null) || (values[4] == null) || !typeof(Brush).IsAssignableFrom(values[0].GetType()) || !typeof(bool).IsAssignableFrom(values[1].GetType()) || !doubleType.IsAssignableFrom(values[2].GetType()) || !doubleType.IsAssignableFrom(values[3].GetType()) || !doubleType.IsAssignableFrom(values[4].GetType())) { return null; } // // Conversion // Brush brush = (Brush)values[0]; bool isIndeterminate = (bool)values[1]; double width = (double)values[2]; double height = (double)values[3]; double trackWidth = (double)values[4]; // if an invalid height, return a null brush if (width <= 0.0 || Double.IsInfinity(width) || Double.IsNaN(width) || height <= 0.0 || Double.IsInfinity(height) || Double.IsNaN(height) ) { return null; } DrawingBrush newBrush = new DrawingBrush(); // Set the viewport and viewbox to the size of the progress region newBrush.Viewport = newBrush.Viewbox = new Rect(0, 0, width, height); newBrush.ViewportUnits = newBrush.ViewboxUnits = BrushMappingMode.Absolute; newBrush.TileMode = TileMode.None; newBrush.Stretch = Stretch.None; DrawingGroup myDrawing = new DrawingGroup(); DrawingContext myDrawingContext = myDrawing.Open(); double drawnWidth = 0.0; // The total width drawn to the brush so far double blockWidth = 6.0; double blockGap = 2.0; double blockTotal = blockWidth + blockGap; // For the indeterminate case, just draw a portion of the width // And animate the brush if (isIndeterminate) { int blocks = (int)Math.Ceiling(width / blockTotal); // The left (X) starting point of the brush double left = -blocks * blockTotal; // Only draw 30% of the blocks double indeterminateWidth = width * .3; // Generate the brush so it wraps correctly // The brush is larger than the rectangle to fill like so: // +-------------+ // [] [] [] __ __ |[] [] [] __ _| // +-------------+ // Translate Brush =>> // To have the marquee line up on the left as the blocks are scrolled off to the right // we need to have the second set of blocks offset from the first by the width of the rect newBrush.Viewport = newBrush.Viewbox = new Rect(left, 0, indeterminateWidth - left, height); // Add an animated translate transfrom TranslateTransform translation = new TranslateTransform(); double milliseconds = blocks * 100; // 100 milliseconds on each position DoubleAnimationUsingKeyFrames animation = new DoubleAnimationUsingKeyFrames(); animation.Duration = new Duration(TimeSpan.FromMilliseconds(milliseconds)); // Repeat every 3 seconds animation.RepeatBehavior = RepeatBehavior.Forever; // Add a keyframe to translate by each block for (int i = 1; i <= blocks; i++) { double x = i * blockTotal; animation.KeyFrames.Add(new DiscreteDoubleKeyFrame(x, KeyTime.Uniform)); } // Set the animation to the XProperty translation.BeginAnimation(TranslateTransform.XProperty, animation); // Set the animated translation on the brush newBrush.Transform = translation; // Draw the Blocks to the left of the brush that are translated into view // during the animation // While able to draw complete blocks, while ((drawnWidth + blockWidth) < indeterminateWidth) { // Draw a block myDrawingContext.DrawRectangle( brush, null, new Rect(left + drawnWidth, 0, blockWidth, height)); drawnWidth += blockTotal; } width = indeterminateWidth; //only need to draw 30% of the blocks drawnWidth = 0.0; //reset drawn width and draw the left blocks } // Draw as many blocks // While able to draw complete blocks, while ( (drawnWidth + blockWidth) < width ) { // Draw a block myDrawingContext.DrawRectangle( brush, null, new Rect(drawnWidth, 0, blockWidth, height)); drawnWidth += blockTotal; } double remainder = width - drawnWidth; // Draw portion of last block when ProgressBar is 100% (ie indicatorWidth == trackWidth) if (!isIndeterminate && remainder > 0.0 && Math.Abs(width - trackWidth) < 1.0e-5) { // Draw incomplete block to fill progress indicator area myDrawingContext.DrawRectangle( brush, null, new Rect(drawnWidth, 0, remainder, height)); } myDrawingContext.Close(); newBrush.Drawing = myDrawing; return newBrush; }
private void createKeyTimeUniformExample() { // <SnippetKeyTimesUniformExample> /* * This rectangle is animated with KeyTimes using Uniform values. * Goes to 100 in the first 3.3 seconds, 100 to * 300 in the next 3.3 seconds, 300 to 500 in the last 3.3 seconds. */ // Create the a rectangle. Rectangle aRectangle = new Rectangle(); aRectangle.Fill = Brushes.Red; aRectangle.Stroke = Brushes.Black; aRectangle.StrokeThickness = 5; aRectangle.Width = 50; aRectangle.Height = 50; // Create a transform to move the rectangle // across the screen. TranslateTransform translateTransform3 = new TranslateTransform(); aRectangle.RenderTransform = translateTransform3; // Create a DoubleAnimationUsingKeyFrames // to animate the transform. DoubleAnimationUsingKeyFrames transformAnimation = new DoubleAnimationUsingKeyFrames(); transformAnimation.Duration = TimeSpan.FromSeconds(10); /* * KeyTime properties are expressed with values of Uniform. When a key time is set to * "Uniform" the total allotted time of the animation is divided evenly between key frames. * In this example, the total duration of the animation is ten seconds and there are four * key frames each of which are set to "Uniform", therefore, the duration of each key frame * is 3.3 seconds (10/3). */ // Animate to 100. transformAnimation.KeyFrames.Add( new LinearDoubleKeyFrame(100, KeyTime.Uniform)); // Animate to 300. transformAnimation.KeyFrames.Add( new LinearDoubleKeyFrame(300, KeyTime.Uniform)); // Animate to 500. transformAnimation.KeyFrames.Add( new LinearDoubleKeyFrame(500, KeyTime.Uniform)); // Start the animation when the rectangle is loaded. aRectangle.Loaded += delegate(object sender, RoutedEventArgs e) { translateTransform3.BeginAnimation(TranslateTransform.XProperty, transformAnimation); }; // </SnippetKeyTimesUniformExample> mainPanel.Children.Add(aRectangle); }
private static void BeginZoomAnimation(double zoomValue) { // TODO Make zoom work when image rotated Point relative = Mouse.GetPosition(ConfigureWindows.GetMainWindow.MainImage); // Calculate new position double absoluteX = relative.X * scaleTransform.ScaleX + translateTransform.X; double absoluteY = relative.Y * scaleTransform.ScaleY + translateTransform.Y; // Reset to zero if value is one, which is reset double newTranslateValueX = zoomValue > 1 ? absoluteX - relative.X * zoomValue : 0; double newTranslateValueY = zoomValue > 1 ? absoluteY - relative.Y * zoomValue : 0; var duration = new Duration(TimeSpan.FromSeconds(.3)); var scaleAnim = new DoubleAnimation(zoomValue, duration) { // Set stop to make sure animation doesn't hold ownership of scaletransform FillBehavior = FillBehavior.Stop }; scaleAnim.Completed += delegate { // Hack it to keep the intended value scaleTransform.ScaleX = scaleTransform.ScaleY = zoomValue; // Make sure value stays correct ZoomValue = 1.0; }; var translateAnimX = new DoubleAnimation(translateTransform.X, newTranslateValueX, duration) { // Set stop to make sure animation doesn't hold ownership of translateTransform FillBehavior = FillBehavior.Stop }; translateAnimX.Completed += delegate { // Hack it to keep the intended value translateTransform.X = newTranslateValueX; }; var translateAnimY = new DoubleAnimation(translateTransform.Y, newTranslateValueY, duration) { // Set stop to make sure animation doesn't hold ownership of translateTransform FillBehavior = FillBehavior.Stop }; translateAnimY.Completed += delegate { // Hack it to keep the intended value translateTransform.Y = newTranslateValueY; }; // Start animations translateTransform.BeginAnimation(TranslateTransform.XProperty, translateAnimX); translateTransform.BeginAnimation(TranslateTransform.YProperty, translateAnimY); scaleTransform.BeginAnimation(ScaleTransform.ScaleXProperty, scaleAnim); scaleTransform.BeginAnimation(ScaleTransform.ScaleYProperty, scaleAnim); }
/// <summary> /// 生成和显示弹窗方法 /// </summary> protected override void Invoke(object parameter) { if (Content == null) { throw new NotFiniteNumberException("Content is null"); } if (Title == null) { throw new NotFiniteNumberException("Title is null"); } object[] args = null; if (Args != null) { args = Args.ToArray(); } // 调取有参构造失败后调取无参构造,待修改 IContentWindow win = null; BaseUserControl content = null; ContentWindow contentWindow = null; //当前打开的窗体 try { content = Content.Assembly.CreateInstance(Content.FullName, true, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, args, null, null) as BaseUserControl; } catch (Exception) { content = Content.Assembly.CreateInstance(Content.FullName) as BaseUserControl; } // 根据弹窗类型反向生成对应的的窗口类 switch (WindowType) { case ContentWindowType.ToolBox: contentWindow = HasOpenedWindow(Title); if (contentWindow != null) { // 若已打开,则使当前窗口弹出至最上层 contentWindow.Topmost = true; return; } else { win = ToolBoxContentWindow.Create(content, Title) .SetContentMargin(ContentMargin) .SetHeight(Height) .SetWidth(Width) .SetTileBackground(TileBackground) .SetIcon(Icon); } break; case ContentWindowType.Document: contentWindow = HasOpenedWindow(Title); if (contentWindow != null) { // 若已打开,则使当前窗口弹出至最上层 contentWindow.Topmost = true; return; } else { win = ConfirmContentWindow.Create(content, Title) .SetContentMargin(ContentMargin) .SetHeight(Height) .SetTileBackground(TileBackground) .SetWidth(Width); } break; default: contentWindow = HasOpenedWindow(Title); if (contentWindow != null) { // 若已打开,则使当前窗口弹出至最上层 contentWindow.Topmost = true; return; } else { if (Title == "麻醉评分") { win = ContentWindow.Create(content, Title, false) .SetContentMargin(ContentMargin) .SetResizeMode(ResizeMode) .SetMinHeight(MinHeight) .SetMinWidth(MinWidth) .SetHeight(Height) .SetWidth(Width) .SetBorderMargin(BorderMargin) .SetTileBackground(TileBackground) .SetIcon(content.Icon); } else { win = ContentWindow.Create(content, Title) .SetContentMargin(ContentMargin) .SetResizeMode(ResizeMode) .SetMinHeight(MinHeight) .SetMinWidth(MinWidth) .SetHeight(Height) .SetWidth(Width) .SetBorderMargin(BorderMargin) .SetTileBackground(TileBackground) .SetIcon(content.Icon); } } break; } //设置内容控制窗体大小 if (!(Height > 0 & Width > 0)) { (win as Window).SizeToContent = SizeToContent.WidthAndHeight; } //边界控制 if (PositionX > 0 || PositionY > 0) { win.SetStartupLocation(WindowStartupLocation.Manual); //防止窗体显示不全 //获取屏幕的边界 double maxWidth = SystemParameters.PrimaryScreenWidth; //得到屏幕整体宽度 double maxHeight = SystemParameters.PrimaryScreenHeight; //得到屏幕整体高度 if (PositionX + Width > maxWidth) { PositionX = maxWidth - Width - 20; } if (PositionY + Height > maxHeight & PositionY - Height > 0) { PositionY = PositionY - Height; } else { if (ContentName.Equals("OperationInterfaceControl")) { } else { PositionY = maxHeight - Height - 5; } } win.SetX(PositionX); win.SetY(PositionY); } else { win.SetStartupLocation(WindowStartupLocation.CenterScreen); } content.CallBack = obj => { if (CallBackCommand != null) { CallBackCommand.Execute(obj); } }; content.Close = () => (win as Window).Close(); content.ParentWindow = (win as Window); var vm = content.DataContext as BaseViewModel; if (vm != null) { vm.Args = args; vm.CloseContentWindowDelegate = () => (win as Window).Close(); } (win as Window).Loaded += ShowContentWindowAction_Loaded; (win as Window).Closed += (s1, e1) => { content.Dispose(); object result = null; if (vm != null) { if (vm.Result != null) { result = vm.Result; } } else { result = content.Result; } // 出发回调函数 if (CallBackCommand != null) { CallBackCommand.Execute(result); } // 设置返回值 if (ContentMessage != null) { ContentMessage.Result = result; } //content.DataContext = null; //content = null; //(win as Window).Content = null; //win = null; }; if (win is ContentWindow) { ContentWindow contentWin = win as ContentWindow; contentWin.ClosingAction = (s1, e1) => { if (e1.Cancel) { return; } if (!contentWin.IsAnimationCloseWindow) { double durationTime = 0.2; switch (WindowAnimation) { case ContentWindowAnimation.FadeIn: e1.Cancel = true; DoubleAnimation daShow = new DoubleAnimation(); daShow.From = 1; daShow.To = 0.4; daShow.Duration = TimeSpan.FromSeconds(durationTime); contentWin.IsAnimationCloseWindow = true; daShow.Completed += (sender, e) => { (s1 as Window).Close(); }; (s1 as Window).BeginAnimation(Window.OpacityProperty, daShow); break; case ContentWindowAnimation.VerticalFloating: TranslateTransform tt = new TranslateTransform(); DoubleAnimation da = new DoubleAnimation(); Duration duration = new Duration(TimeSpan.FromSeconds(durationTime)); (s1 as Window).RenderTransform = tt; tt.Y = 0; da.To = (s1 as Window).ActualHeight; da.Duration = duration; contentWin.IsAnimationCloseWindow = true; da.Completed += (sender, e) => { (s1 as Window).Close(); }; tt.BeginAnimation(TranslateTransform.YProperty, da); e1.Cancel = true; break; case ContentWindowAnimation.HorizontalFloating: TranslateTransform ttHorizontal = new TranslateTransform(); DoubleAnimation daHorizontal = new DoubleAnimation(); Duration durationHorizontal = new Duration(TimeSpan.FromSeconds(durationTime)); (s1 as Window).RenderTransform = ttHorizontal; daHorizontal.From = 0; daHorizontal.To = -(s1 as Window).ActualWidth; daHorizontal.Duration = durationHorizontal; contentWin.IsAnimationCloseWindow = true; daHorizontal.Completed += (sender, e) => { (s1 as Window).Close(); }; ttHorizontal.BeginAnimation(TranslateTransform.XProperty, daHorizontal); e1.Cancel = true; break; } } else { e1.Cancel = false; } }; } if (this.Owner != null) { win.SetOwner(Owner); } if (IsModal) { win.ShowDialog(); } else { win.Show(); } }