且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF 中的 Windows 窗体绘制等效事件

更新时间:2023-12-06 09:49:22

您正在寻找 DrawingVisual 班级

来自第一个链接:

DrawingVisual 是一个轻量级的绘图类,用于渲染形状、图像或文本.此类被认为是轻量级的,因为它不提供布局或事件处理,从而提高了其性能.因此,绘图是背景和剪贴画的理想选择.

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.

您还可以访问 PolyLine 类 您可以向其中添加点集合.此示例是经过修改的 MSDN论坛示例


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;

    }
}

和修改后的 MSDN 示例:


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

}