Search code examples
.netwpfcanvasdrawinginkcanvas

How to draw a free hand shape (random) & text printing on wpf canvas


I am developing a paint application. I am using Canvas control as whiteboard.

I want to use InkCanvas kind of functionality in WPF canvas, means I want to draw a free hand shape on Canvas. How can I do this ? I also want to save in as *.JPG

Second question is to draw the fonts like we do in MS Paint ? Can I integrate FontDialogBox in it ? If yes, How ?

Thanking You !!!


Solution

  • Here's a simple example of drawing a line on a canvas and how to add a textBlock object.

    Example:

        <StackPanel>
          <Canvas MouseLeftButtonDown="myCanvas_MouseLeftButtonDown" MouseMove="myCanvas_MouseMove"
    x:Name="inkCanvas" Width="400" Height="200"> </Canvas>
          <Button Height="20" Width="30" x:Name="AddTextBtn" Click="AddTextBtn_Click">AddText</Button>
        </StackPanel>
    

    Code Behind:

    private Point _startPoint;
    private Polyline _line;
    
    private void myCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
      _startPoint = e.GetPosition(myCanvas);
      _line = new Polyline();
      _line.Stroke = new SolidColorBrush(Colors.Black);
      _line.StrokeThickness = 2.0;
    
      myCanvas.Children.Add(_line);
    }
    
    private void myCanvas_MouseMove(object sender, MouseEventArgs e)
    {
      if (e.LeftButton == MouseButtonState.Pressed)
      {
        Point currentPoint = e.GetPosition(myCanvas);
        if (_startPoint != currentPoint)
        {
            _line.Points.Add(currentPoint);
        }
      } 
    }
    
    private void AddTextBtn_Click(object sender, RoutedEventArgs e)
    {
      // Show Font Dialog Box
    
      TextBlock tb = new TextBlock();
      tb.FontFamily = new FontFamily("Arial");
      tb.FontSize = 14;
      tb.Text = "SampleText";
    
      // Set position on canvas:
      Canvas.SetTop(tb,100);
      Canvas.SetLeft(tb, 50);
    
      myCanvas.Children.Add(tb);
    }
    

    But there is no pure WPF Font Chooser. You can either use the one from WinForms or have a look around there are lots of pure Xaml implementations. E.g. link

    Saving as jpg: use RenderTargetBitmap or CroppedBitmap; See link on SO