none
Draw line in canvas RRS feed

  • Question

  • I have two questions with this.

    My form as a grid and in one column and row of my grid i have my canvas.

    How do I find the X and Y position of this canvas?

    How can I draw a line within this canvas?

    Sunday, April 15, 2012 5:45 AM

Answers

  • I suppose you are trying to draw the line from code, so i would first and foremost find the object in the Grid that contains the canvas, and then 

    line = new Line();
    line.Stroke = Brushes.LightSteelBlue;
    
    line.X1 = 1;
    line.X2 = 50;
    line.Y1 = 1;
    line.Y2 = 50;
    
    line.StrokeThickness = 2;
    myCanvas.Children.Add(line);

    Hope this helps.


    Developing is part of being a developer.

    Sunday, April 15, 2012 11:27 AM
  • Hi Kiwis,

    To find the position of Canvas, there is the TransformToAncestor method:

    Point relativePoint = Canvas1.TransformToAncestor(rootVisual) 
                                 
    .Transform(new Point(0, 0)); 

    Where Canvas is the element which you want to get position, and rootVisual is Application.Current.MainWindow or whatever you want the position relative to.

    Hope it helps.

    Have a nice day.


    Annabella Luo[MSFT]
    MSDN Community Support | Feedback to us

    Monday, April 16, 2012 6:24 PM
    Moderator

All replies

  • Hi kiwis,

    There are properties available like Canvas.Top, Canvas.Left, etc, which will give you position of canvas.

    And about lines, you can draw inside canvas as:

    <Canvas Height="300" Width="300">
      <!-- Draws a diagonal line from (10,10) to (50,50). -->
      <Line
        X1="10" Y1="10"
        X2="50" Y2="50"
        Stroke="Black"
        StrokeThickness="4" />
    </Canvas>


    Regards, http://shwetamannjain.blogspot.com

    Sunday, April 15, 2012 10:31 AM
  • I suppose you are trying to draw the line from code, so i would first and foremost find the object in the Grid that contains the canvas, and then 

    line = new Line();
    line.Stroke = Brushes.LightSteelBlue;
    
    line.X1 = 1;
    line.X2 = 50;
    line.Y1 = 1;
    line.Y2 = 50;
    
    line.StrokeThickness = 2;
    myCanvas.Children.Add(line);

    Hope this helps.


    Developing is part of being a developer.

    Sunday, April 15, 2012 11:27 AM
  • Hi Kiwis,

    To find the position of Canvas, there is the TransformToAncestor method:

    Point relativePoint = Canvas1.TransformToAncestor(rootVisual) 
                                 
    .Transform(new Point(0, 0)); 

    Where Canvas is the element which you want to get position, and rootVisual is Application.Current.MainWindow or whatever you want the position relative to.

    Hope it helps.

    Have a nice day.


    Annabella Luo[MSFT]
    MSDN Community Support | Feedback to us

    Monday, April 16, 2012 6:24 PM
    Moderator