c# – Create coordinate grid on Canvas

Question:

There is Canvas. You can drop images on it. Then move them, resize them, etc. Question. What is the best way to create and display a grid on Canvas, say 10 by 10 pixels? And how then to make "sticking" of the controls located on canvas to it? Provided that:

  1. the canvas's Background property is occupied by the background color (which is logical), and you can't put a brush there.

  2. With DrawingBrush there are generally problems, in the sense that on old hardware, on win XP, the grid drawn through the DrawingBrush does not want to be drawn. And it is necessary. Drawn on more modern computers.

I am clarifying at the request of the workers. We need the most optimal way (algorithm) to create a drawn grid on a Canvas element using net3.5. And a way to stick canvas elements to it. I thought that simply drawing lines on the canvas would slow down.

Answer:

If you need a variable size grid, subscribe to Canvas 's resizing and draw manually:

<Grid>
    <Canvas x:Name="Background"
            Width="{Binding ActualWidth, ElementName=MainCanvas}"
            Height="{Binding ActualHeight, ElementName=MainCanvas}"
            SizeChanged="UpdateBackPattern"/>
    <Canvas x:Name="MainCanvas"/>
</Grid>
public YourControlConstructor()
{
    InitializeComponent();
    UpdateBackPattern(null, null);
}

void UpdateBackPattern(object sender, SizeChangedEventArgs e)
{
    var w = Background.ActualWidth;
    var h = Background.ActualHeight;

    Background.Children.Clear();
    for (int x = 10; x < w; x += 10)
        AddLineToBackground(x, 0, x, h);
    for (int y = 10; y < h; y += 10)
        AddLineToBackground(0, y, w, y);
}

void AddLineToBackground(double x1, double y1, double x2, double y2)
{
    var line = new Line()
    {
        X1 = x1, Y1 = y1,
        X2 = x2, Y2 = y2,
        Stroke = Brushes.Black,
        StrokeThickness = 1,
        SnapsToDevicePixels = true
    };
    line.SetValue(RenderOptions.EdgeModeProperty, EdgeMode.Aliased);
    Background.Children.Add(line);
}

For "snapping" you need to check the coordinates of the object being moved and if they are close to the grid (i.e. x % <шаг сетки> < <расстояние прилипания> or x % <шаг сетки> > <шаг сетки> - <расстояние прилипания> ) bring its coordinate to a multiple of the grid size.

Scroll to Top