WPF Rectangle movement with Animation - wpf

I have a requirement of moving dynamically created rectangles dynamically.
I am almost done with my implementation, and if I write the code below for each of the rectangle dynamically, I am able to achieve the desired result.
The code below moves the desired rectangle by 50 pixels on X Axis.
TranslateTransform translateTransform1 = new TranslateTransform(50, 0); aRectangle.RenderTransform = translateTransform1;
The problem is I want this to be animated. The code below is written to have the same rectanle moved with animation, but gives entirelly different result all together. Any help will be much appreciated. I want it to manage through code as my rectangles are going to be dynamic.
TranslateTransform translateTransform1 = new TranslateTransform(50, 0);
Duration duration = new Duration(new TimeSpan(0, 0, 0, 1, 0));
DoubleAnimation anim = new DoubleAnimation(30, duration);
translateTransform1.BeginAnimation(TranslateTransform.XProperty, anim);
aRectangle.RenderTransform = translateTransform1;

Try
Duration duration = new Duration(new TimeSpan(0, 0, 0, 1, 0));
DoubleAnimation anim = new DoubleAnimation(30, duration);
aRectangle.RenderTransform = new TranslateTransform();
aRectangle.BeginAnimation(TranslateTransform.XProperty, anim);

Related

Rotate Part of a model WPF

I'm developing a flight simulator and have come across the problem of animating the individual pieces of the airplane (i.e. propeller, elevator, rudder, etc...). I created a class that stores the parts of the planes, which contains GeometryModel and a ModelVisual3D that is constructed from an STL file. When I apply the rotation to the specific part, nothing happens in the application. Full code can be found at: https://github.com/espina7/CSProblems/blob/main/MainWindow.xaml.cs\
public Part RotatePart()
{
//Console.WriteLine("Rotating Part");
Part temp;
temp = this;
AxisAngleRotation3D axisAngle = new AxisAngleRotation3D(new Vector3D(1, 0, 0), 10);
RotateTransform3D myRotate = new RotateTransform3D(axisAngle);
Vector3DAnimation myVectorAnimation = new Vector3DAnimation(new Vector3D(-1, -1, -1), new Duration(TimeSpan.FromMilliseconds(500)));
myVectorAnimation.RepeatBehavior = RepeatBehavior.Forever;
myRotate.Rotation.BeginAnimation(AxisAngleRotation3D.AxisProperty, myVectorAnimation);
Transform3DGroup partGroup = new Transform3DGroup();
partGroup.Children.Add(this.part.Transform);
partGroup.Children.Add(myRotate);
temp.part.Transform = partGroup;
temp.recalculateNormals();
return temp;
}

Is it possible to turn off antialiasing when using ImageBrush tiling?

Is it possible to turn off anti-aliasing in WPF when using an ImageBrush?
Given the following code:
var handleImage = new BitmapImage(new Uri($"pack://application:,,,/Resources/myimage.png"));
var imageBrush = new ImageBrush(handleImage);
imageBrush.AlignmentY = AlignmentY.Top;
imageBrush.AlignmentX = AlignmentX.Left;
imageBrush.Stretch = Stretch.Uniform;
imageBrush.Viewport = new Rect(0, 0, _handleImage.Width, _handleImage.Height);
imageBrush.ViewportUnits = BrushMappingMode.Absolute;
imageBrush.TileMode = TileMode.Tile;
drawingContext.DrawRectangle(imageBrush, null, new Rect(0, 0, width, height));
Gives me something like:
But I'm expecting:
WPF's default antialiasing makes it look terrible. I've tried UseLayoutRounding=true, SnapsToDevicePixels=true, RenderOptions.SetBitmapScalingMode(this, BitmapScalingMode.HighQuality),
RenderOptions.SetBitmapScalingMode(this, BitmapScalingMode.NearestNeighbor) RenderOptions.SetEdgeMode(this, EdgeMode.Unspecified); on the window. The only one that changes any visual difference is BitmapScalingMode.NearestNeighbor however it still looks odd and the tiling overlaps itself.
EDIT: Download full working sample: WpfImageBrushExample.zip
The problem here was that the BitmapImage width and height were different fractional numbers - in this case it was 5.333 x 6x666 instead of the expected 4 x 5 pixels. If I use _handleImage.PixelWidth and _handleImage.PixelHeight the problem is fixed and I don't get weird aliasing under any of those rendering options set.
var handleImage = new BitmapImage(new Uri($"pack://application:,,,/Resources/myimage.png"));
var imageBrush = new ImageBrush(handleImage);
imageBrush.AlignmentY = AlignmentY.Top;
imageBrush.AlignmentX = AlignmentX.Left;
imageBrush.Stretch = Stretch.Uniform;
imageBrush.Viewport = new Rect(0, 0, _handleImage.PixelWidth, _handleImage.PixelHeight);
imageBrush.ViewportUnits = BrushMappingMode.Absolute;
imageBrush.TileMode = TileMode.Tile;
drawingContext.DrawRectangle(imageBrush, null, new Rect(0, 0, width, height));
Produces:

WPF Clear Region on a Drawing Context?

So I am producing a transparent PNG using a DrawingContext and DrawingVisual.
Inside the DrawingContext, I drew a rectange.
I would now like to "cut out" a circle inside of the rectangle. How do I do this? I did not find any functions in drawing context to clear a region.
You can try using CombinedGeometry to combine 2 geometries (each time). It has GeometryCombineMode allowing you to specify some logic combination. In this case what you need is GeometryCombineMode.Xor. The intersection of the Rect and the Ellipse (cirlce) will be cut out. Here is the simple code demonstrating it:
DrawingVisual dv = new DrawingVisual();
using (var dc = dv.RenderOpen()) {
var rect = new Rect(0, 0, 300, 200);
var cb = new CombinedGeometry(GeometryCombineMode.Xor,
new RectangleGeometry(rect),
new EllipseGeometry(new Point(150, 100), 50, 50));
dc.DrawGeometry(Brushes.Blue, null, cb);
}
I hope you know how to render the DrawingVisual. You can use some RenderTargetBitmap to capture it into some kind of BitmapSource and then you have many ways to show this bitmap.
Here is the screenshot:
The Black region means the color is transparent.
In case you want to cut out some complex image (such as drawn text or image). You can turn the CombinedGeometry into some kind of OpacityMask (type of Brush). We can turn it into a DrawingBrush and this brush can be used as OpacityMask which can be passed into DrawingContext.PushOpacityMask method:
DrawingVisual dv = new DrawingVisual();
using (var dc = dv.RenderOpen()) {
var rect = new Rect(0, 0, 300, 200);
var cb = new CombinedGeometry(GeometryCombineMode.Xor,
new RectangleGeometry(rect),
new EllipseGeometry(new Point(150, 100), 50, 50));
var mask = new DrawingBrush(new GeometryDrawing(Brushes.Blue, null, cb));
dc.PushOpacityMask(mask);
dc.DrawImage(someImage, rect);
dc.DrawText(new FormattedText("Windows Presentation Foundation",
System.Globalization.CultureInfo.CurrentCulture,
System.Windows.FlowDirection.LeftToRight,
new Typeface("Lucida Bright"), 30, Brushes.Red){
MaxTextWidth = rect.Width,
MaxTextHeight = rect.Height,
TextAlignment = TextAlignment.Center
}, new Point());
}
Note that the rect should have the size of your whole drawing. Then positioning the hole and other drawn stuff will be exact as what you want.
Finally the DrawingVisual also has a useful property called Clip which is a Geometry. So you can prepare some CombinedGeometry and assign it to DrawingVisual.Clip property.
Suppose you already have your DrawingVisual (with some drawn stuff including text, images, ...). The following code will punch a hole through it:
//prepare the geometry, which can be considered as the puncher.
var rect = new Rect(0, 0, 300, 200);
var cb = new CombinedGeometry(GeometryCombineMode.Xor,
new RectangleGeometry(rect),
new EllipseGeometry(new Point(150, 100), 50, 50));
//punch the DrawingVisual
yourDrawingVisual.Clip = cb;

WPF Storyboard works well, except for the first time it runs. Why?

I'm doing a Surface Application.
And there I have something like a bulletin board where little cards with news on it are pinned on.
On click they shall fly out of the board and scale bigger.
My storyboard works well, except for the first time it runs. It's not a smooth animation then but it scales to its final size immediately and it's the same with the orientation-property. Just the center-property seems to behave correctly.
This is an example for one of my Storyboards doing that:
Storyboard stb = new Storyboard();
PointAnimation moveCenter = new PointAnimation();
DoubleAnimationUsingKeyFrames changeWidth = new DoubleAnimationUsingKeyFrames();
DoubleAnimationUsingKeyFrames changeHeight = new DoubleAnimationUsingKeyFrames();
DoubleAnimationUsingKeyFrames changeOrientation = new DoubleAnimationUsingKeyFrames();
moveCenter.From = News1.ActualCenter;
moveCenter.To = new Point(250, 400);
moveCenter.Duration = new Duration(TimeSpan.FromSeconds(1.0));
moveCenter.FillBehavior = FillBehavior.Stop;
stb.Children.Add(moveCenter);
Storyboard.SetTarget(moveCenter, News1);
Storyboard.SetTargetProperty(moveCenter, new PropertyPath(ScatterViewItem.CenterProperty));
changeWidth.Duration = TimeSpan.FromSeconds(1);
changeWidth.KeyFrames.Add(new EasingDoubleKeyFrame(266, KeyTime.FromTimeSpan(new System.TimeSpan(0, 0, 1))));
changeWidth.FillBehavior = FillBehavior.Stop;
stb.Children.Add(changeWidth);
Storyboard.SetTarget(changeWidth, News1);
Storyboard.SetTargetProperty(changeWidth, new PropertyPath(FrameworkElement.WidthProperty));
changeHeight.Duration = TimeSpan.FromSeconds(1);
changeHeight.KeyFrames.Add(new EasingDoubleKeyFrame(400, KeyTime.FromTimeSpan(new System.TimeSpan(0, 0, 1))));
changeHeight.FillBehavior = FillBehavior.Stop;
stb.Children.Add(changeHeight);
Storyboard.SetTarget(changeHeight, News1);
Storyboard.SetTargetProperty(changeHeight, new PropertyPath(FrameworkElement.HeightProperty));
changeOrientation.Duration = TimeSpan.FromSeconds(1);
changeOrientation.KeyFrames.Add(new EasingDoubleKeyFrame(0, KeyTime.FromTimeSpan(new System.TimeSpan(0, 0, 1))));
changeOrientation.FillBehavior = FillBehavior.Stop;
stb.Children.Add(changeOrientation);
Storyboard.SetTarget(changeOrientation, News1);
Storyboard.SetTargetProperty(changeOrientation, new PropertyPath(ScatterViewItem.OrientationProperty));
stb.Begin(this);
News1.Center = new Point(250, 400);
News1.Orientation = 0;
News1.Width = 266;
News1.Height = 400;
Pin1.Visibility = Visibility.Collapsed;
news1IsOutside = true;
Scroll1.IsEnabled = true;
What's wrong with it?
The Problem
The essence of the problem is that you are calling stb.Begin() and then immediately changing News1.Width, etc. Unfortunately stb.Begin() is not guaranteed to start the animations immediately: At times it does so in a dispatcher callback.
What is happening to you is that the first time your storyboard executes, stb.Begin() schedules a dispatcher callback to start the animations and immediately returns. The next four lines of your code update the values:
News1.Center = new Point(250, 400);
News1.Orientation = 0;
News1.Width = 266;
News1.Height = 400;
When the animations actually start in the dispatcher callback they see the new values and use those as their starting values. This causes the object appears to jump to the new value immediately.
For example, changeWidth declares a keyframe that animates the value to 266:
changeWidth.KeyFrames.Add(new EasingDoubleKeyFrame(266, ...
And later the initial width is set to 266:
News1.Width = 266;
So if the storyboard is delayed starting, the width will animate from 266 to 266. In other words, it will not change. If you later use another animation to change News1.Width to something other than 266 and then run the changeWidth animation, it will work.
Your moveCenter animation works reliably because it actually sets its From value to the current value:
moveCenter.From = News1.ActualCenter;
moveCenter.To = new Point(250, 400);
Thus the animation always starts at the old center, even if the News1.Center = new Point(250,400) once the animation has started.
The Solution
Just as you set "From" on your PointAnimation, you can also set an initial value in your other animations. This is done by adding a key frame at time=0 specifying the current width:
changeWidth.Duration = TimeSpan.FromSeconds(1);
changeWidth.KeyFrames.Add(new DiscreteDoubleKeyframe(News1.Width, KeyTime.Paced));
changeWidth.KeyFrames.Add(new EasingDoubleKeyFrame(266, KeyTime.Paced));
This code uses the fact that KeyTime.Paced automatically results in 0% and 100% if there are two key frames. In fact, setting the first frame as KeyFrame.Paced will always be equivalent to KeyTime.FromTimeSpan(TimeSpan.Zero).
Another solution might be to use FillBehavior.HoldEnd, then hook up to the Storyboard.Completed event and:
Set the local values as you originally did
Call Storyboard.Remove
This would also have the advantage that the local values will be accessible from the properties.

Saving an Image from WPF's WebBrowser control - how do you do it?

everyone. There's probably a simple solution to this but I can't seem to find one. I'm playing around with the WebBrowser control in WPF that ships with Visual Studio 2010 and am trying to save an image that might appear on a webpage to disk programmatically.
Many thanks in advance!
Luck
Add System.Drawing as reference and perform the following oprations in the method that should capture the image:
Rect bounds = VisualTreeHelper.GetDescendantBounds(browser1);
System.Windows.Point p0 = browser1.PointToScreen(bounds.TopLeft);
System.Drawing.Point p1 = new System.Drawing.Point((int)p0.X, (int)p0.Y);
Bitmap image = new Bitmap((int)bounds.Width, (int)bounds.Height);
Graphics imgGraphics = Graphics.FromImage(image);
imgGraphics.CopyFromScreen(p1.X, p1.Y,
0, 0,
new System.Drawing.Size((int)bounds.Width,
(int)bounds.Height));
image.Save("C:\\a.bmp", ImageFormat.Bmp);
Here are the adaptions to solution of #luvieere:
WebBrowser browser1;
browser1 = this.Browser;
// I used the GetContentBounds()
Rect bounds = VisualTreeHelper.GetContentBounds(browser1);
// and the point to screen command for the top-left and the bottom-right corner
System.Windows.Point pTL = browser1.PointToScreen(bounds.TopLeft);
System.Windows.Point pBR = browser1.PointToScreen(bounds.BottomRight);
System.Drawing.Bitmap image = new
// The size is then calculated as difference of the two corners
System.Drawing.Bitmap(
System.Convert.ToInt32(pBR.X - pTL.X),
System.Convert.ToInt32(pBR.Y - pTL.Y));
System.Drawing.Graphics imgGraphics = System.Drawing.Graphics.FromImage(image);
imgGraphics.CopyFromScreen(pTL.X, pTL.Y, 0, 0, new System.Drawing.Size(image.Width, image.Height));
fileName = System.IO.Path.GetFileNameWithoutExtension(fileName) + ".bmp";
image.Save(fileName, System.Drawing.Imaging.ImageFormat.Bmp);
For those, who prefer VB-dialect
Dim browser1 As WebBrowser
browser1 = Me.Browser
Dim bounds As Rect = VisualTreeHelper.GetContentBounds(browser1)
Dim pTL As System.Windows.Point = browser1.PointToScreen(bounds.TopLeft)
Dim pBR As System.Windows.Point = browser1.PointToScreen(bounds.BottomRight)
Dim image As System.Drawing.Bitmap = New System.Drawing.Bitmap(CInt(pBR.X - pTL.X), CInt(pBR.Y - pTL.Y))
Dim imgGraphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(image)
imgGraphics.CopyFromScreen(pTL.X, pTL.Y, 0, 0, New System.Drawing.Size(image.Width, image.Height))
fileName = IO.Path.GetFileNameWithoutExtension(fileName) & ".bmp"
image.Save(fileName, System.Drawing.Imaging.ImageFormat.Bmp)

Resources