DevExpress It provides a powerful graphic drawing tool , It can be used to draw various graphics , Like the flow chart 、 Organization chart, etc , This essay introduces XtraDiagram.DiagramControl Use , And use code to control its properties , And the user-defined operation using the graphic mold , Realize the drawing and processing of some simple process graphics .

DiagramControl Is similar to Visio Drawing controls for , I used to 2006 It has been used for years Visio Secondary development , At that time, we still used VB6 + VIsio2003 Two times of development , Later it was modified to C# + Visio Secondary development ,DiagramControl The object model of is very similar Visio Related object model of , For example, for the shape of the toolbar , Call it a mold (Stencil),Visio It is also called Stencil, DiagramControl Many of the interface names still use Stencil Name it , Therefore, it is estimated that a lot of Visio Knowledge of object design , If you are right about Visio Interested in secondary development , You can refer to my essay 《Visio Secondary development 》, There is a lot of relevant content in it .

If you want to know the relevant knowledge and use of this control , It should be a good tutorial to refer to the cases and descriptions on the official website (https://docs.devexpress.com/WindowsForms/118290/controls-and-libraries/diagrams/getting-started ).

1、DiagramControl Use of control

DiagramControl Is an interface control , similar Visio SDK Inside DrawingControl The existence of , It can be used to draw graphics , Display and hiding of various windows , And tracking the handling of various events .

DiagramControl Control to the form , Some attribute windows will be added automatically , The buttons in the drawing tool in the upper row were added by me , Used to test the control of some properties of the control .

1) Display and hide of attribute window ( Fold )

This is controlled by diagramControl1.OptionsView.PropertiesPanelVisibility Property to control the property window .

It displays some system location and content information , And some custom information windows , Later I will introduce how to customize the properties of these molds .

Code handled by buttons , We can show or hide this window .

// Toggles the display or closing of the properties window 
var status = diagramControl1.OptionsView.PropertiesPanelVisibility;
diagramControl1.OptionsView.PropertiesPanelVisibility = (status == PropertiesPanelVisibility.Visible ? PropertiesPanelVisibility.Collapsed : PropertiesPanelVisibility.Visible);

2) Show or hide the mold shape window

Mold shaped window , It is placed in a panel , We only need to control the display or hiding of the panel , As shown in the following code .

// Toggles the display or closing of the mold shape window 
var status = diagramToolboxDockPanel1.Visibility;
diagramToolboxDockPanel1.Visibility = (status == DevExpress.XtraBars.Docking.DockVisibility.Visible ? DevExpress.XtraBars.Docking.DockVisibility.Hidden : DevExpress.XtraBars.Docking.DockVisibility.Visible);

Or through the control Toolbar Property to control , Same effect .

// Toggles the display or closing of the mold shape window 
var status = this.diagramControl1.OptionsView.ToolboxVisibility;
this.diagramControl1.OptionsView.ToolboxVisibility = status == ToolboxVisibility.Closed ? ToolboxVisibility.Full : ToolboxVisibility.Closed;

3) Zoom in or out of the window to show or hide

Similarly, we can also control the display or hiding of the zoom in and zoom out window , It is also a common window for drawing graphics . We just need to judge or set diagramControl1.OptionsView.ShowPanAndZoomPanel Properties will do , As shown in the following code .

// Toggles the display or closing of the zoom window 
var status = diagramControl1.OptionsView.ShowPanAndZoomPanel;
diagramControl1.OptionsView.ShowPanAndZoomPanel = !status;

4) Processing of other properties

in addition , We can control some properties , Realize the adjustment of ruler 、 grid 、 Read only view, etc .

// Whether to display ruler 
this.diagramControl1.OptionsView.ShowRulers = this.chkRuler.Checked;
// Show grid or not
this.diagramControl1.OptionsView.ShowGrid = this.chkGrid.Checked;
// Read only view
this.diagramControl1.OptionsProtection.IsReadOnly = this.chkReadOnly.Checked;

2、 Processing events of drawing

When drawing figures , Generally speaking, we may need to switch the click mode or the connection line mode , So you can use its properties ActiveTool Set it up . In click mode , You can drag the graph 、 Zoom in and out 、 Rotation, etc , In cable mode , The connection point is highlighted , Easy to draw connection lines automatically .

private void btnPointerMode_Click(object sender, EventArgs e)
{
diagramControl1.OptionsBehavior.ActiveTool = diagramControl1.OptionsBehavior.PointerTool;
} private void btnConnectorMode_Click(object sender, EventArgs e)
{
diagramControl1.OptionsBehavior.ActiveTool = diagramControl1.OptionsBehavior.ConnectorTool;
}

Of course , We can also control by analyzing the behavior of the mouse , If you hover or place the mouse over the drawing , Automatically switch the mode to the connection line mode , Otherwise, it is the click mode , Then you only need to judge the movement behavior of the mouse to automatically process , As shown in the following code .

        /// <summary>
/// Automatically switch to connection point mode for graphics
/// </summary>
private void diagramControl1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
return; DiagramItem item = diagramControl1.CalcHitItem(e.Location);
if (item == null)
{
diagramControl1.OptionsBehavior.ActiveTool = diagramControl1.OptionsBehavior.PointerTool;
return;
}
else if (item is DiagramConnector)
{
diagramControl1.OptionsBehavior.ActiveTool = diagramControl1.OptionsBehavior.ConnectorTool;
return;
} Rect itemBounds = new Rect(new Point(item.Position.X, item.Position.Y), new Size(item.Width, item.Height));
PointFloat documentPoint = diagramControl1.PointToDocument(new PointFloat(e.Location));
DiagramHitInfo[] hitInfo = diagramControl1.CalcHitInfo(documentPoint);
if (itemBounds.Contains(new Point(documentPoint.X, documentPoint.Y)))
{
itemBounds.Inflate(-5, -5);
if (!itemBounds.Contains(new Point(documentPoint.X, documentPoint.Y)))
{
diagramControl1.OptionsBehavior.ActiveTool = diagramControl1.OptionsBehavior.ConnectorTool;
return;
}
}
diagramControl1.OptionsBehavior.ActiveTool = diagramControl1.OptionsBehavior.PointerTool;
}

In addition, the saving of graphics xml、PNG、PDF The processing and loading code is as follows .

/// <summary>
/// preservation XML And picture files
/// </summary>
private void SaveXml()
{
var xml = Path.Combine(Application.StartupPath, "MyFlowShapes.xml");
diagramControl1.SaveDocument(xml); var pngFile = Path.Combine(Application.StartupPath, "MyFlowShapes.png");
diagramControl1.ExportDiagram(pngFile);
}
private void btnLoadXml_Click(object sender, EventArgs e)
{
var xml = FileDialogHelper.OpenXml();
if(!string.IsNullOrEmpty(xml))
{
diagramControl1.LoadDocument(xml);
}
}

The effect of the final case is as follows .

3、 Register custom shapes

In the actual development of graphics rendering , We can need to create some specified shape stencils , Then we can usually store it in XML in , Then load the control , The following code is used to register custom shapes .

/// <summary>
/// Register custom shapes .
/// Custom graphics are based on XML Save as a file , Graphics need to be as specified XML Format to draw
/// </summary>
private void LoadShapes2()
{
var projectName = "SmallExampleDemo.Examples.XtraDiagram";
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(projectName + ".CustomContainers.xml"))
{
var stencil = DiagramStencil.Create(MyStencilId, MyStencilName, stream, shapeName => shapeName);
DiagramToolboxRegistrator.RegisterStencil(stencil);
}
diagramControl1.SelectedStencils = new StencilCollection(MyStencilId);//(MyStencilId, BasicShapes.StencilId);
}

We just need to set the selected graphics , Others in need can be found in More Shapes Choose from .

If we need to display custom properties in the properties window , Then we need some code development to achieve .

We need to inherit one first DiagramShape Subclasses of , Then implement your own custom attribute definitions , As shown in the following code .

Handling of custom attributes , You need to implement... In the event

diagramControl1.CustomGetEditableItemProperties += DiagramControl_CustomGetEditableItemProperties;

By judging it, you can realize the display and processing of custom attributes

void DiagramControl_CustomGetEditableItemProperties(object sender, DiagramCustomGetEditableItemPropertiesEventArgs e)
{
if (e.Item is DiagramShapeEx)
{
e.Properties.Add(TypeDescriptor.GetProperties(typeof(DiagramShapeEx))["Status"]);
e.Properties.Add(TypeDescriptor.GetProperties(typeof(DiagramShapeEx))["TypeName"]);
}
}

Then we can register to create our own mold shape collection , As shown in the following code .

/// <summary>
/// Create a custom stencil
/// </summary>
/// <returns></returns>
DiagramStencil CreateCustomDrawShapesStencil()
{
var stencilId = "CustomedFlowShape";
var stencilName = " flow chart ";
var shapeSizeSmall = new Size(100, 37.5);
var shapeSize = new Size(100, 75); DiagramControl.ItemTypeRegistrator.Register(typeof(DiagramShapeEx));
var stencil = new DiagramStencil(stencilId, stencilName); // Process type
stencil.RegisterTool(new FactoryItemTool("StartEnd", () => " The process begins ", diagram => {
var shape = new DiagramShapeEx(BasicFlowchartShapes.StartEnd, " The process begins ");
shape.Appearance.BackColor = Color.Red;
return shape;
}, shapeSizeSmall));
stencil.RegisterTool(new FactoryItemTool("Decision", () => " Process conditions ", diagram => {
var shape = new DiagramShapeEx(BasicFlowchartShapes.Decision, " Process conditions ");
shape.Appearance.BackColor = Color.FromArgb(199, 115, 1);//Color.Red;
return shape;
}, shapeSize));

These two processes begin , Process conditions , We are directly from  BasicFlowchartShapes Borrowed from the collection , Build your own custom objects , The object created by default is square .

If we need to dynamically build other custom types , We can specify its color and other styles , To build different types of graphics .

// Add related process nodes circularly 
var procNames = new List<string> { " The examination and approval ", " file ", " Read and do ", " jointly sign ", " The leader's instructions are distributed "};
// Define several initialization color sequences
var colors = new List<Color> { Color.DeepSkyBlue, Color.ForestGreen, Color.Violet, Color.Yellow, Color.Blue, Color.Orange, Color.Indigo, Color.Purple, Color.Black, Color.Brown, Color.Pink };
int i = 0;
foreach (string name in procNames)
{
var shapeId = string.Format("Process_{0}", i++); stencil.RegisterTool(new FactoryItemTool(shapeId, () => name, diagram =>
{
var shape = new DiagramShapeEx(name, Status.Inactive);
var index = procNames.IndexOf(name);
var color = colors[index % 10];//Color.Red;
var fontColor = (color == Color.Yellow) ? Color.Black : Color.White; // It doesn't work
//shape.ThemeStyleId = GetStyle(index); // from Accent1 The pattern starts DiagramShapeStyleId.Styles[index];//
shape.Appearance.BackColor = color;
shape.Appearance.BorderSize = 3;
shape.Appearance.Font = new Font(" Song style ", 12f, FontStyle.Bold);
shape.Appearance.ForeColor = fontColor;
return shape;
}, shapeSize));
}

In this way, there are graphic objects of different colors .

According to these, we can draw our own flow charts , And also according to the information of the database , Perform dynamic rendering display .

utilize XtraDiagram.DiagramControl More related articles on drawing and controlling process graphics

  1. Quartz2D Common drawing of graphics : line 、 polygon 、 round

    UI senior Quartz2D http://ios.itcast.cn  iOS college master drawRect: Use of methods Common drawing of graphics : line . polygon . round The setting of drawing state : Text color . Line width, etc Graphic context ...

  2. HTML5 Canvas ( Drawing of filled graphics ) closePath, fillStyle, fill

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  3. utilize canvas Shadow function and double line technique to draw the effect of rail transit large screen project

    utilize canvas Shadow function and double line technique to draw the effect of rail transit large screen project Preface Recently, the company received a demand for track system , It is necessary to display the real-time position of metro lines and trains on the large screen . Since it's a big screen project , The visual effect is of course the first priority , Let's take a look at ...

  4. utilize Java operation Jenkins API Realize to Jenkins Details of the control of

    This article is reprinted from Java operation Jenkins API Realize to Jenkins Details of the control of Introduction Due to the need to take advantage of Jenkins long-range API operation Jenkins To do some column operations , Take time to study ...

  5. 【HarmonyOS】【xml】 Use xml Draw the video playback control bar

    This paper records HarmonyOS Use xml Draw the video playback control bar The renderings are as follows The code is as follows Click to view the code <?xml version="1.0" encoding="utf-8& ...

  6. utilize Microsoft VC++6.0 Of MFC Drawing tools to achieve the drawing of simple graphics

          MFC Powerful operation function , It has complete drawing function .       stay Windows On the platform , The application's graphical device interface (graphics device interface,GDI) Is abstracted as a device context (Dev ...

  7. utilize CSS3 clip-path Crop various shapes .

    'clip-path' yes css3 A powerful attribute of , We can use it to draw various shapes , Of course, it's not just these , Let's take a look at its powerful functions . The first part is about clip-path Inside polygon function , We can go through ...

  8. utilize matplotlib Of plot Function to achieve image rendering

    An experiment of pattern recognition , It is required to draw the diagram of Bayesian decision . Here I use python Medium matplotlib Library to achieve the fitting of graph lines . Mainly for matplotlib You can refer to the blog for the use of :webary If you want to draw a three-dimensional image, you can refer to ...

  9. Qt The figure of ( Draw beautiful arcs )

    sketch Introduction to 2D drawing before synthesis , We must have a deep understanding of some basic drawings , Let's implement some beautiful graphics rendering . sketch circular effect Source code arc effect Source code Text effect Source code rotate effect Source code circular Often , I ...

  10. GDI+ In graphics and image processing technology Pen and Brush Simple use and drawing of simple graphics (C#)

    1.Graphics Graphics The object is GDI+ Drawing surface , So in Windows To use... In a form application GDI+ Create drawings , You have to create Graphics. Register a form Paint After the event ,Graphics ...

Random recommendation

  1. Arima Fit function ,se appear NaN problem

    R Language Arima Function fitting model ,se( Standard error ) appear NaN The problem of . Referring to the information on the Internet , Although I don't quite understand what it means , But such a model cannot be used . Reference resources :http://stackoverflow.com/questio ...

  2. TCP And UDP agreement

    Transmission control protocol (Transmission Control Protocol, TCP) And user datagram protocol (User Datagram Protocol, UDP) It's a typical transport layer protocol . Transport layer protocol is based on network layer ...

  3. yum Error during installation Errno 14 Couldn&#39;t resolve host terms of settlement ( turn )

    In the installation mlocate I found that I kept reporting errors , The error contents are as follows Downloading Packages:http://mirrors.163.com/centos/6.5/os/i386/Packages ...

  4. oracle Table import to powerDesigner in

    Not busy recently , I used to use powerDesigner Look at the structure of the watch , I haven't imported it myself , Try today oracle Table import to powerDesigner Step 2 : 1.File--->reverse Enginne ...

  5. php take html Turn to picture

    On the server side, parse the compiled html Convert to picture . because html It is generally resolved by the client browser , The server can't parse it directly html Code . So we need to use php Class libraries and extensions fulfill this requirement . The file conversion process is html -> ...

  6. Build.gradle Detailed configuration description of

    from :http://blog.csdn.net/u012246458/article/details/51722624 apply plugin: 'com.android.application'/ ...

  7. TextView With the help of Linkify, Use custom mode to set Links

    http://my.oschina.net/fengheju/blog/176105 TextView yes android In a more commonly used control , It has a very interesting feature , Can pass android:autoL ...

  8. win10 Open blue Because of its configuration information ( In the registry ) Incomplete or damaged

    At the administrator command prompt, type the following command : Dism /Online /Cleanup-Image /ScanHealth This command will scan all system files and compare them with the official system files , Scan the computer for inconsistencies . Dism ...

  9. hdu 5826 physics Physics problems

    physics Topic linking : http://acm.hdu.edu.cn/showproblem.php?pid=5826 Description There are n balls on a smoo ...

  10. xml Class explanation