Windows Form Paint equivalent event in WPF

独自空忆成欢 提交于 2019-12-04 13:53:13
Mark Hall

You are looking for the DrawingVisual Class

From first Link:

The DrawingVisual is a lightweight drawing class that is used to render shapes, images, or text. This class is considered lightweight because it does not provide layout or event handling, which improves its performance. For this reason, drawings are ideal for backgrounds and clip art.


You also have access to a PolyLine Class that you can add a point Collection to. This example is a modified MSDN Forum example

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        float x0 = 100f;
        float y0 = 100f;
        Polyline myPoly = new Polyline();
        PointCollection polyPoints = myPoly.Points;
        Point[] points = new Point[200];

        for (int j = 0; j < 200; j++)
        {
            points[j] = new Point();
            points[j].X = x0 + j;
            points[j].Y = y0 -
            (float)(Math.Sin((2 * Math.PI * j) / 200) * (200 / (2 * Math.PI)));
        }

        for (int i = 0; i < points.Length ; i++)
        {
            polyPoints.Add(points[i]);
        }

        myPoly.Stroke = Brushes.Green;
        myPoly.StrokeThickness = 5;
        StackPanel mainPanel = new StackPanel();
        mainPanel.Children.Add(myPoly);
        this.Content = mainPanel;

    }
}

And a Modified MSDN example:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        float x0 = 100f;
        float y0 = 100f;
        Point[] points = new Point[200];

        for (int j = 0; j < 200; j++)
        {
            points[j] = new Point();
            points[j].X = x0 + j;
            points[j].Y = y0 -
            (float)(Math.Sin((2 * Math.PI * j) / 200) * (200 / (2 * Math.PI)));
        }

        DrawingBrush db = new DrawingBrush(CreateDrawingVisualRectangle(points).Drawing);
        StackPanel mainPanel = new StackPanel();
        mainPanel.Background = db;
        this.Content = mainPanel;

    }

    private DrawingVisual CreateDrawingVisualRectangle( Point[] pointarray)
    {
        DrawingVisual drawingVisual = new DrawingVisual();

        // Retrieve the DrawingContext in order to create new drawing content.
        DrawingContext drawingContext = drawingVisual.RenderOpen();

       // Create a rectangle and draw it in the DrawingContext.
       for (int i = 0; i < pointarray.Length-1; i++)
       {
           drawingContext.DrawLine(new Pen(new SolidColorBrush(Colors.Blue), 2), pointarray[i], pointarray[i + 1]);
       }

       // Persist the drawing content.
       drawingContext.Close();

       return drawingVisual;
     }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!