How to make an image(or a rectangle) follow a Spline - c#

I have a project that I need to make an image follow a spline.
I build the spline using Graphics.DrawCurve through an array of Points.
I'm trying to use PointAnimationUsingPath but I can't seem to get it to work. Apparently it doesn't work in C# with Windows form.
Can someone give me a light on how to do this?
Thank you All.
-----EDIT-----
Change to a WPF UserControl as recommend in comments.
Still need some help as the shape does not move exactly following the dots, below my code:
public partial class SplineBox : UserControl
{
Point[] finalPoint;
public SplineBox()
{
InitializeComponent();
}
public void MoveShape(Point[] _path)
{
// Create a NameScope for the page so that
// we can use Storyboards.
NameScope.SetNameScope(this, new NameScope());
// Create the EllipseGeometry to animate.
EllipseGeometry animatedEllipseGeometry =
new EllipseGeometry(new Point(10, 100), 15, 15);
// Register the EllipseGeometry's name with
// the page so that it can be targeted by a
// storyboard.
this.RegisterName("AnimatedEllipseGeometry", animatedEllipseGeometry);
// Create a Path element to display the geometry.
Path ellipsePath = new Path();
ellipsePath.Data = animatedEllipseGeometry;
ellipsePath.Fill = Brushes.Blue;
ellipsePath.Margin = new Thickness(15);
SplineCanvas.Children.Add(ellipsePath);
this.Content = SplineCanvas;
// Create the animation path.
PathGeometry animationPath = new PathGeometry();
PathFigure pFigure = new PathFigure();
pFigure.StartPoint = _path[0];
PolyBezierSegment pBezierSegment = new PolyBezierSegment();
for (int p = 1; p < _path.Length; p++)
{
pBezierSegment.Points.Add(_path[p]);
}
pFigure.Segments.Add(pBezierSegment);
animationPath.Figures.Add(pFigure);
// Freeze the PathGeometry for performance benefits.
animationPath.Freeze();
// Create a PointAnimationgUsingPath to move
// the EllipseGeometry along the animation path.
PointAnimationUsingPath centerPointAnimation = new PointAnimationUsingPath();
centerPointAnimation.PathGeometry = animationPath;
centerPointAnimation.Duration = TimeSpan.FromSeconds(5);
centerPointAnimation.RepeatBehavior = RepeatBehavior.Forever;
// Set the animation to target the Center property
// of the EllipseGeometry named "AnimatedEllipseGeometry".
Storyboard.SetTargetName(centerPointAnimation, "AnimatedEllipseGeometry");
Storyboard.SetTargetProperty(centerPointAnimation,
new PropertyPath(EllipseGeometry.CenterProperty));
// Create a Storyboard to contain and apply the animation.
Storyboard pathAnimationStoryboard = new Storyboard();
pathAnimationStoryboard.RepeatBehavior = RepeatBehavior.Forever;
pathAnimationStoryboard.AutoReverse = true;
pathAnimationStoryboard.Children.Add(centerPointAnimation);
// Start the Storyboard when ellipsePath is loaded.
ellipsePath.Loaded += delegate (object sender, RoutedEventArgs e)
{
// Start the storyboard.
pathAnimationStoryboard.Begin(this);
};
}
public void Paint(ScreenObject _spline)
{
List<Point> points = new List<Point>();
if (true)
{
var spline = _spline;
foreach (System.Windows.Point point in spline.SplineAnchors)
{
Point tempP = new Point((int)point.X, (int)point.Y);
points.Add(tempP);
}
finalPoint = points.ToArray();
//Pen pen = new Pen(Color.FromArgb(255, 0, 0, 255), 1);
//e.Graphics.DrawCurve(pen, finalPoint);
foreach (Point p in finalPoint)
{
// Create a red Ellipse.
Ellipse myEllipse = new Ellipse();
// Create a SolidColorBrush with a red color to fill the
// Ellipse with.
SolidColorBrush mySolidColorBrush = new SolidColorBrush();
// Describes the brush's color using RGB values.
// Each value has a range of 0-255.
mySolidColorBrush.Color = Color.FromArgb(255, 100, 255, 0);
myEllipse.Fill = mySolidColorBrush;
myEllipse.StrokeThickness = 2;
myEllipse.Stroke = Brushes.Black;
// Set the width and height of the Ellipse.
myEllipse.Width = 10;
myEllipse.Height = 10;
myEllipse.Margin = new Thickness(p.X - 5, p.Y - 5, 0, 0);
//e.Graphics.DrawRectangle(pen, new Rectangle(p.X - 5, p.Y - 5, 10, 10));
//e.Graphics.FillRectangle(Brushes.Red, new Rectangle(p.X - 5, p.Y - 5, 10, 10));
SplineCanvas.Children.Add(myEllipse);
}
}
}
}

Related

Object not shown on Canvas (WPF Application)

In this Application, i have a car class with a method called Spawn (which should draw the object on a Canvas which i defined in the XAML file). I call the Method in MainWindow, but when I run my program, there is no car being drawn onto the Canvas.
Here is the Spawn method:
public void Spawn(Canvas cvs)
{
cvs = new Canvas();
cvs.Children.Clear();
carBody.Width = 70;
carBody.Height = 120;
carBody.Background = new SolidColorBrush(Color);
Canvas.SetLeft(carBody, SpawnLocation.X);
Canvas.SetTop(carBody, SpawnLocation.Y);
Rectangle[] tires = new Rectangle[4];
Rectangle[] windows = new Rectangle[2];
Label lblBrand = new Label();
RotateTransform rotation = new RotateTransform();
// Reifen
tires[0] = new Rectangle()
{
Fill = Brushes.Black,
Width = 20,
Height = 30
};
Canvas.SetLeft(tires[0], -9);
Canvas.SetTop(tires[0], 18);
tires[1] = new Rectangle()
{
Fill = Brushes.Black,
Width = 20,
Height = 30
};
Canvas.SetLeft(tires[1], 61);
Canvas.SetTop(tires[1], 18);
tires[2] = new Rectangle()
{
Fill = Brushes.Black,
Width = 20,
Height = 30
};
Canvas.SetLeft(tires[2], -9);
Canvas.SetTop(tires[2], 80);
tires[3] = new Rectangle()
{
Fill = Brushes.Black,
Width = 20,
Height = 30
};
Canvas.SetLeft(tires[3], 61);
Canvas.SetTop(tires[3], 80);
// Fenster
windows[0] = new Rectangle() // Front
{
Fill = Brushes.White,
Width = 50,
Height = 40
};
Canvas.SetLeft(windows[0], 0);
Canvas.SetTop(windows[0], 0);
windows[1] = new Rectangle() // rear
{
Fill = Brushes.White,
Width = 50,
Height = 50
};
Canvas.SetLeft(windows[1], 0);
Canvas.SetTop(windows[1], 0);
// Label Automarke
lblBrand.Width = 40;
lblBrand.Height = 23;
lblBrand.Content = Brand;
// Add2Canvas
for (int i = 0; i < tires.Length; i++)
carBody.Children.Add(tires[i]);
for (int i = 0; i < windows.Length; i++)
carBody.Children.Add(windows[i]);
carBody.Children.Add(lblBrand);
if (Direction == "nord")
{
rotation.Angle = 0;
rotation.CenterX = SpawnLocation.X;
rotation.CenterY = SpawnLocation.Y;
carBody.RenderTransform = rotation;
}
else if (Direction == "süd")
{
rotation.Angle = 180;
rotation.CenterX = SpawnLocation.X;
rotation.CenterY = SpawnLocation.Y;
carBody.RenderTransform = rotation;
}
else if (Direction == "west")
{
rotation.Angle = 90;
rotation.CenterX = SpawnLocation.X;
rotation.CenterY = SpawnLocation.Y;
carBody.RenderTransform = rotation;
}
else if (Direction == "ost")
{
rotation.Angle = 270;
rotation.CenterX = SpawnLocation.X;
rotation.CenterY = SpawnLocation.Y;
carBody.RenderTransform = rotation;
}
cvs.Children.Add(carBody);
}
Calling the methodMainWindow:
Car car1;
public MainWindow()
{
InitializeComponent();
car1 = new Car("Audi", Colors.Red);
car1.Direction = "west";
car1.SpawnLocation = new Point(550, 340);
car1.Spawn(gameScreen);
}
Thanks in advance!
Fixed it! I initialized the argmument of my Spawn method, it now works after I deleted it.
My method looked like this first:
public void Spawn(Canvas cvs)
{
cvs = new Canvas();
cvs.Children.Clear();
carBody.Width = 70;
I initialized my the Argument, but since i don't wanna create a new Canvas, i deleted these two first lines of my method.
public void Spawn(Canvas cvs)
{
carBody.Width = 70;
carBody.Height = 120;
carBody.Background = new SolidColorBrush(Color);
Now its working fine.

C# ToolStripProfessionalRender, event OnRenderItemText applied only on the first item

I'm drawing a custom toolstrip using ToolStripProfessionalRender and editing the OnRenderItemText event as follows:
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
e.Item.ForeColor = Clr.White;
e.Item.TextAlign = ContentAlignment.MiddleLeft;
e.Item.Alignment = ToolStripItemAlignment.Left;
base.OnRenderItemText(e);
if (e.Item.GetType() == typeof(ToolStripDropDownButton))
{
ToolStripDropDownButton tsmi = (ToolStripDropDownButton)e.Item;
if (tsmi.HasDropDownItems && tsmi.OwnerItem == null)
{
Rectangle bounds = tsmi.Bounds;
bounds.X = bounds.Right - 25;
bounds.Width = 25;
bounds.Y = 10;
// Draw the corner
Graphics G = e.Graphics;
SolidBrush brushw = new SolidBrush(Color.FromArgb(70,70,70));
Point[] points =
{
new Point(bounds.Right - 3, bounds.Height - 11), // point top right
new Point(bounds.Right - 3, bounds.Bottom - 14), // point bottom right
new Point(bounds.Right - 10, bounds.Bottom - 14) // point bottom left
};
G.FillPolygon(brushw, points);
}
}
}
and basically the output i'm trying to obtain is the following:
So drawing a little triangle on the bottom right corner when i got a ToolStripDropDownButton. The problem is that the little triangle is drawn only first item.
To end up the question i draw this toolstrip dynamically using a function that adds a dropdownbutton at each call.
ToolStripDropDownButton m_Item = new ToolStripDropDownButton(text, image);
m_Item.ImageAlign = ContentAlignment.MiddleCenter;
m_Item.ImageScaling = ToolStripItemImageScaling.None;
m_Item.Name = name;
m_Item.ForeColor = Color.White;
m_Item.BackColor = Color.FromArgb(95, 95, 95);
m_Item.Padding = new Padding(5);
m_Item.ShowDropDownArrow = false;
m_Item.Paint += new PaintEventHandler(this.PaintButtonBorder);
if (tabPage != null)
m_Item.Click += (sender, e) => AddClickTab(sender, e, tabPage);
((ToolStripDropDownMenu)m_Item.DropDown).ShowImageMargin = false;
((ToolStripDropDownMenu)m_Item.DropDown).ShowCheckMargin = false;
((ToolStripDropDownMenu)m_Item.DropDown).Cursor = Cursors.Hand;
toolStrip1.Items.Add(m_Item);
if (SubItems != null)
{
for(int i = 0; i < SubItems.Length; i++)
{
object[] subitem = (object[])SubItems[i];
FnAddToolStripMenuItem(
subitem[0].ToString(),
subitem[1].ToString(),
(Bitmap)subitem[2],
m_Item,
(TabPage)subitem[3]
);
}
}
Am i missing some "new" maybe?
Override the OnRenderItemText method only to draw the text part as it says, and/or to set the default properties used when rendering the text. To change the look and the shape of the arrows of the dropdown items, override the OnRenderArrow method.
Example
using System.Drawing;
using System.Drawing.Drawing2D;
protected override void OnRenderArrow(ToolStripArrowRenderEventArgs e)
{
// Optional: to be the default color of the arrows.
e.ArrowColor = Color.FromArgb(70, 70, 70);
if (e.Item is ToolStripDropDownButton item && item.OwnerItem == null)
{
var g = e.Graphics;
var r = new Rectangle(item.Bounds.Width - 10, item.Bounds.Height - 10, 8, 8);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.PixelOffsetMode = PixelOffsetMode.Half;
using (var br = new SolidBrush(e.ArrowColor))
g.FillPolygon(br, new[]
{
new Point(r.Left, r.Bottom),
new Point(r.Right, r.Top),
new Point(r.Right, r.Bottom)
});
g.SmoothingMode = SmoothingMode.None;
g.PixelOffsetMode = PixelOffsetMode.Default;
}
else
base.OnRenderArrow(e);
}
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e)
{
e.Item.ForeColor = Color.White;
e.Item.TextAlign = ContentAlignment.MiddleLeft;
e.Item.Alignment = ToolStripItemAlignment.Left;
base.OnRenderItemText(e);
}
Make sure to enable the ShowDropDownArrow property of the dropdown buttons. So comment this m_Item.ShowDropDownArrow = false;.
If you are also interested to change the color according to the current state of the dropdown button (Selected, Pressed), then you can do for example:
using (var br = new SolidBrush(item.Selected
? Color.FromArgb(150, 150, 150) : item.Pressed
? Color.FromArgb(100, 100, 100) :
Color.FromArgb(70, 70, 70)))
//...

Double Animation - What is TranslateTransform "Width Change" Definition in C# UWP?

I am using MSDN example to setup the animation of Width of a Rectangle in C3 UWP.
Here is the code of the sample:
private void Create_And_Run_Animation()
{
// Create a red rectangle that will be the target
// of the animation.
Rectangle myRectangle = new Rectangle();
myRectangle.Width = 0;
myRectangle.Height = 20;
SolidColorBrush myBrush = new SolidColorBrush(Colors.Yellow);
myRectangle.Fill = myBrush;
// Create the transform
TranslateTransform stretchTransform = new TranslateTransform();
stretchTransform.X = 0;
stretchTransform.Y = 0;
myRectangle.RenderTransform = stretchTransform;
// Add the rectangle to the tree.
DefaultLayout.Children.Add(myRectangle);
myRectangle.Name = "myWidthAnimatedRectangle";
// Create a duration of 2 seconds.
Duration duration = new Duration(TimeSpan.FromSeconds(2));
// Create two DoubleAnimations and set their properties.
DoubleAnimation myDoubleAnimation = new DoubleAnimation();
myDoubleAnimation.From = 0.0;
myDoubleAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(3000));
Storyboard justintimeStoryboard = new Storyboard();
justintimeStoryboard.Duration = duration;
justintimeStoryboard.Children.Add(myDoubleAnimation);
Storyboard.SetTarget(myDoubleAnimation, stretchTransform);
Storyboard.SetTargetName(myDoubleAnimation, myRectangle.Name);
// Set the X property of the Transform to be the target property
Storyboard.SetTargetProperty(myDoubleAnimation, "X");
myDoubleAnimation.To = 300.0;
// Make the Storyboard a resource.
DefaultLayout.Resources.Add("justintimeStoryboard", justintimeStoryboard);
// Begin the animation.
justintimeStoryboard.Begin();
}
However, on Build, what it does is move the object and not change its width.
I need to animate width change.
However, on Build, what it does is move the object and not change its width. I need to animate width change.
Your code was used to animate the Rectangle's position, not its width. You could specify a default value for its width and animate its ScaleTransform.
If you have to use DoubleAnimation to animate its width, you need to set EnableDependentAnimation to true. Please check the following code sample:
private void Create_And_Run_Animation()
{
// Create a red rectangle that will be the target
// of the animation.
Rectangle myRectangle = new Rectangle();
myRectangle.Width = 10;
myRectangle.Height = 20;
SolidColorBrush myBrush = new SolidColorBrush(Colors.Yellow);
myRectangle.Fill = myBrush;
// Add the rectangle to the tree.
DefaultLayout.Children.Add(myRectangle);
myRectangle.Name = "myWidthAnimatedRectangle";
DoubleAnimation myDoubleAnimation = new DoubleAnimation();
myDoubleAnimation.From = 0.0;
myDoubleAnimation.Duration = new Duration(TimeSpan.FromMilliseconds(3000));
Storyboard justintimeStoryboard = new Storyboard();
Storyboard.SetTargetProperty(myDoubleAnimation, "(Rectangle.Width)");
Storyboard.SetTargetName(myDoubleAnimation, myRectangle.Name);
myDoubleAnimation.To = 300.0;
myDoubleAnimation.EnableDependentAnimation = true;
justintimeStoryboard.Children.Add(myDoubleAnimation);
// Make the Storyboard a resource.
DefaultLayout.Resources.Add("justintimeStoryboard", justintimeStoryboard);
// Begin the animation.
justintimeStoryboard.Begin();
}

Unable to Remove Child in WPF

I have a uniform grid that has rectangles dynamically added to it. I want to remove a particular rectangle, but I am getting the following error when trying to pass it to the Remove method:
Cannot convert from 'System.Drawing.Rectangle' to 'System.Windows.UIElement'
My code is:
Rectangle swatch = (Rectangle)ug_Thumbnails.FindName("s_" + _instance);
ug_Thumbnails.Children.Remove(swatch);
I tried casting, and got an error saying that you couldn't do it.
EDIT: Per request, here's the code to create the rectangle:
System.Windows.Shapes.Rectangle swatch = new System.Windows.Shapes.Rectangle();
swatch.Width = 50;
swatch.Height = 50;
swatch.Margin = new Thickness(0, 5, 5, 0);
swatch.StrokeThickness = 1;
swatch.Stroke = System.Windows.Media.Brushes.Gray;
swatch.Name = "s_" + name.ToString();
double groupsize = 100 / colors.Count();
DrawingBrush blackBrush = new DrawingBrush();
DrawingGroup checkersDrawingGroup = new DrawingGroup();
List<SolidColorBrush> brushes = colors;
double location = 0;
for (int i = 0; i < colors.Count(); i++)
{
GeometryDrawing drawing = new GeometryDrawing(brushes[i], null,
new RectangleGeometry(new Rect(location, 0, groupsize, groupsize)));
checkersDrawingGroup.Children.Add(drawing);
location += groupsize;
}
blackBrush.Drawing = checkersDrawingGroup;
swatch.Fill = blackBrush;
swatch.MouseUp += new MouseButtonEventHandler(loadSwatchResources);
ug_Thumbnails.Children.Add(swatch);
You need to use the Rectangle in System.Windows.Shapes when trying to reference a rectangle in WPF. This is specifically for rectangles in WPF and as such is a bit different than the System.Drawing rectangle class. You should be able to cast to this version of rectangle since it derives from FrameworkElement. See http://msdn.microsoft.com/en-us/library/system.windows.shapes.rectangle(v=vs.110).aspx for more info.

What points to be used for Drawing Hexagonal Shaped Button

Using below code I am able to draw arrow shaped button(shown below) ,but I want to draw hexagone(shown below as result image) ,so that I can use png image of size 175x154 as button image ,What Points I need to use to draw this ? and i need to to draw 6 such buttons ,how do i achieve this ?
private void Parent_Load(object sender, EventArgs e)
{
// Define the points in the polygonal path.
Point[] pts = {
new Point( 20, 60),
new Point(140, 60),
new Point(140, 20),
new Point(220, 100),
new Point(140, 180),
new Point(140, 140),
new Point( 20, 140)
};
// Make the GraphicsPath.
GraphicsPath polygon_path = new GraphicsPath(FillMode.Winding);
polygon_path.AddPolygon(pts);
// Convert the GraphicsPath into a Region.
Region polygon_region = new Region(polygon_path);
// Constrain the button to the region.
btnExam.Region = polygon_region;
// Make the button big enough to hold the whole region.
btnExam.SetBounds(
btnExam.Location.X,
btnExam.Location.Y,
pts[3].X + 5, pts[4].Y + 5);
}
The input should be a Rectangle which contains the Hexagonal shape, from that input we will calculate the Points for your Hexagonal shape, something like this:
public Point[] GetPoints(Rectangle container){
Point[] points = new Point[6];
int half = container.Height / 2;
int quart = container.Width/4;
points[0] = new Point(container.Left + quart, container.Top);
points[1] = new Point(container.Right - quart, container.Top);
points[2] = new Point(container.Right, container.Top + half);
points[3] = new Point(container.Right - quart, container.Bottom);
points[4] = new Point(container.Left + quart, container.Bottom);
points[5] = new Point(container.Left, container.Top + half);
return points;
}
private void Parent_Load(object sender, EventArgs e) {
//This should be placed first
// Make the button big enough to hold the whole region.
btnExam.SetBounds( btnExam.Location.X, btnExam.Location.Y, 100, 100);
// Make the GraphicsPath.
GraphicsPath polygon_path = new GraphicsPath(FillMode.Winding);
polygon_path.AddPolygon(GetPoints(btnExam.ClientRectangle));
// Convert the GraphicsPath into a Region.
Region polygon_region = new Region(polygon_path);
// Constrain the button to the region.
btnExam.Region = polygon_region;
}
You should update the Region whenever your btnExam's Size changes, so you should define some method called UpdateRegion and call it in a SizeChanged event handler:
private void UpdateRegion(){
GraphicsPath polygon_path = new GraphicsPath(FillMode.Winding);
polygon_path.AddPolygon(GetPoints(btnExam.ClientRectangle));
btnExam.Region = new Region(polygon_path);
}
//SizeChanged event handler for your btnExam
private void btnExam_SizeChanged(object sender, EventArgs e){
UpdateRegion();
}
//Then you just need to change the size of your btnExam in Parent_Load
private void Parent_Load(object sender, EventArgs e) {
//The button should be square
btnExam.SetBounds( btnExam.Location.X, btnExam.Location.Y, 100, 100);
}
Is this what you mean?
var xDisp = 10;
var yDisp = 10;
var length = 10;
var ls32 = (int)(length * Math.Sqrt(3) / 2.0);
var half = (int)(length / 2.0);
var points = new[]
{
new Point(xDisp + length, yDisp),
new Point(xDisp + half, yDisp + ls32),
new Point(xDisp - half, yDisp + ls32),
new Point(xDisp - length, yDisp),
new Point(xDisp - half, yDisp - ls32),
new Point(xDisp + half, yDisp - ls32)
};

Categories

Resources