In traditional Windows Forms programming, if we need to create some more personalized controls, we often need to customize the drawing of the control (rewrite OnPaint, etc.), that is, the need to frequently use graphics objects. In WPF, we can easily write very distinctive interface elements using XAML, and it seems that the days of previous drawing controls using the graphics object's handwriting code are getting farther away. In fact, in WPF, if we need a low-level custom drawing, we would need a class named DrawingContext. corresponding to the OnPaint method is the OnRender (of course, you can also draw in other places).
In the Uielement.onrender (DrawingContext DrawingContext) method, the DrawingContext object is provided directly, and we can use it to do all kinds of drawing operations like the previous Graphics object, It is worth noting the following:
1, in our code, we can't call the OnRender method directly, and it will be laid out and drawn by the system's asynchronous invocation (this is different from Win32).
2, we cannot directly create DrawingContext instances, but we can use Drawinggroup.open and drawingvisual.renderopen to get them.
3, our drawing is not real time, in fact our drawing will be saved to a drawing instruction set by the graphics system at some point.
For reference to the following code, we redefine a canvas drawing:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows;
using System.Globalization;
namespace CustomPaint
{
class MyCanvas : Canvas
{
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
dc.DrawRectangle(Brushes.LightBlue, new Pen(Brushes.Red, 1),
new Rect(new Point(10, 10), new Size(100, 50)));
dc.DrawText(new FormattedText("my canvas", CultureInfo.CurrentCulture,
FlowDirection.LeftToRight, new Typeface("Tahoma"), 20, Brushes.Green),
new Point(50,25));
}
}
}
The effect is as follows:
In customizing your drawing in WPF (ii) We'll go into more detail on how to customize the drawing in WPF, thanks.