2012-06-13 11 views
3

我正在开发绘画应用程序。我正在使用Canvas控件作为白板。如何在wpf画布上绘制自由手形(随机)和文本打印

我想在WPF画布中使用InkCanvas类的功能,这意味着我想在画布上绘制一个自由的手形。我怎样才能做到这一点 ?我还想保存为* .JPG

第二个问题是绘制像我们在MS Paint中做的字体?我可以在其中整合FontDialogBox吗?如果是,如何?

感谢你!!!

回答

5

下面是一个在画布上绘制线条以及如何添加textBlock对象的简单示例。

实施例:

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

代码背后:

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); 
} 

但没有纯WPF字体选择。您可以使用WinForms中的一个,或者查看大量纯Xaml实现。例如。 link

另存为jpg:使用RenderTargetBitmap或CroppedBitmap; See link on SO

+0

感谢您的回答,如何将自由手绘制到“画布”上,我不想使用InckCanvas? – Xyroid

+0

我用一个基本样本更新了我的答案: 您可以将当前Point添加到在鼠标移动事件期间在画布上绘制的多段线... HTH – SvenG

+0

非常感谢您给我解决方案.... – Xyroid