3

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 !!!

Xyroid
  • 463
  • 5
  • 19

1 Answers1

9

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

Community
  • 1
  • 1
SvenG
  • 5,155
  • 2
  • 27
  • 36
  • Thanks for your answer, what about free hand drawing onto 'canvas', i don't wanna use InckCanvas ? – Xyroid Jun 13 '12 at 09:23
  • I've updated my answer with a basic sample: You can add the current Point to a polyline which is drawn on a canvas during the mousemove event ... HTH – SvenG Jun 13 '12 at 10:18