I draw a rectangle and I need to divide this rectangle into 2 parts. I am trying to use line in order to divide it but I dont know why I can not see the line.
Rectangle rect = new Rectangle();
rect.Fill= Colors.Blue;
rect.Width=100;
rect.Margin = new Thikness (0,40,0,0);
grid.Children.Add(rect);
Line line = new Line();
line.Stroke = Colors.Black;
line.StrokeThickness=1;
line.X1=2;
line.X2=7;
line.Y1=41;
line.Y2=41;
grid.Children.Add(line);
Do you have any idea that how can I add a line on the rectangle?
Here is how you would divide it vertically:-
a) you were drawing a line 5 pixels in width but it was not visible because your line was of stroke Black and the page background was also Black so the line was hidden. The line was drawn from (2,41) to (7,41).
b) your rectangle was in the center of the page, 100 pixels wide and as tall as the page and thus the line which was on the top left did not intersect with the rectangle which was in the center
c) I would recommend the use of a Canvas since you can easily set Top and Left pixel positions of each item on the Canvas
I modified your code in the following way:-
Rectangle rect = new Rectangle();
rect.Fill = new SolidColorBrush(Colors.Blue);
rect.Width = 100;
rect.Height = 200;
Canvas.SetLeft(rect, 200);
Canvas.SetTop(rect, 20);
LayoutRoot.Children.Add(rect);
Line line = new Line();
line.Stroke = new SolidColorBrush(Colors.White);
line.StrokeThickness = 1;
line.X1 = Canvas.GetLeft(rect) + rect.Width / 2;
line.X2 = Canvas.GetLeft(rect) + rect.Width / 2;
line.Y1 = Canvas.GetTop(rect);
line.Y2 = Canvas.GetTop(rect) + rect.Height;
LayoutRoot.Children.Add(line);
1) LayoutRoot is my Canvas in the XAML...I have just changed it from Grid to Canvas in the default page template.
2) I have used these two lines to set the position of the rect on the Canvas. You can change this to any hardcoded/programmatically calculated value.
Canvas.SetLeft(rect, 200);
Canvas.SetTop(rect, 20);
3) I have calculated the X and Y positions of the line here
line.X1 = Canvas.GetLeft(rect) + rect.Width / 2;
line.X2 = Canvas.GetLeft(rect) + rect.Width / 2;
line.Y1 = Canvas.GetTop(rect);
line.Y2 = Canvas.GetTop(rect) + rect.Height;
The X1 and X2 positions are basically the Left position of the rect plus half of the rect width
The Y1 and Y2 positions are the rect top and rect top plus rect height.
Add these two elements to the Canvas and it will work