1.自定义节点类
public class IconNode : DiagramNode
{
}
2.节点类定义一个初始化静态函数
static IconNode()
{
defaultIcon = new Bitmap(48, 48);
Graphics graphics = Graphics.FromImage(defaultIcon);
Font font = new Font("Arial", 48, FontStyle.Bold, GraphicsUnit.Pixel);
graphics.FillRectangle(Brushes.Transparent, 0, 0, 48, 48);
graphics.DrawString("?", font, Brushes.Black, 0, 0);
font.Dispose();
graphics.Dispose();
}
3.定义一个公共的构造函数
public IconNode(Diagram diagram) : base(diagram)
{
icon = defaultIcon;
label = "Label";
format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
Bounds = new RectangleF(Bounds.Location, CalculateSize());
}
4.重载DrawLocal方法
public override void DrawLocal(IGraphics graphics, RenderOptions options)
{
Rectangle iconSizePixels = new Rectangle(
0, 0, icon.Width, icon.Height);
RectangleF imageSize = MindFusion.Utilities.DeviceToDoc(
graphics, iconSizePixels);
// Draw the icon at the top-middle
graphics.DrawImage(icon,
Bounds.X + Bounds.Width / 2 - imageSize.Width / 2, Bounds.Y);
// Draw the label at the bottom
RectangleF labelBounds = RectangleF.FromLTRB(
Bounds.X, Bounds.Y + imageSize.Height,
Bounds.Right, Bounds.Bottom);
graphics.DrawString(label,
Font, Brushes.Black, labelBounds, format);
}
5.重载DrawShadowLocal方法
public override void DrawShadowLocal(IGraphics graphics, RenderOptions options)
{
}
6.定义自定义属性
public Image Icon
{
get { return icon; }
set
{
icon = value;
Bounds = new RectangleF(Bounds.Location, CalculateSize());
}
}
public string Label
{
get { return label; }
set
{
label = value;
Bounds = new RectangleF(Bounds.Location, CalculateSize());
}
}
7.设置可序列化节点实例
// Enable serialization of IconNode instances
Diagram.RegisterItemClass(typeof(IconNode), "IconNode", 1);
8.执行序列化
protected override void SaveTo(
System.IO.BinaryWriter writer, PersistContext ctx)
{
base.SaveTo(writer, ctx);
// Save the label using the standard .NET BinaryWriter
writer.Write(label);
// which stores the contents of shared images only once.
ctx.SaveImage(icon);
}
protected override void LoadFrom(
System.IO.BinaryReader reader, PersistContext ctx)
{
base.LoadFrom(reader, ctx);
label = reader.ReadString();
icon = ctx.LoadImage();
}
9.设置可交互式地绘制节点对象
// Let users draw IconNode objects
diagramView.CustomNodeType = typeof(IconNode);
diagramView.Behavior = Behavior.Custom;
10.添加自定义节点绘制到click事件里
private void diagram_Clicked(object sender, DiagramEventArgs e)
{
IconNode iconNode = new IconNode(diagram);
diagram.Nodes.Add(iconNode);
iconNode.Move(e.MousePosition.X, e.MousePosition.Y);
}