Spread.NET includes two different shape engines that allow you to add and manage shapes on a worksheet:
- Legacy Shape Engine
- Enhanced Shape Engine
The enhanced shape engine is designed to behave similarly to Excel’s shape feature. In this article, we demonstrate how to work with shapes using the legacy shape engine, including adding shapes, attaching data, customizing rendering, and handling shape-related events.
Before working with shapes, disable the enhanced shape engine using the following code:
fpSpread1.Features.EnhancedShapeEngine = false;
1. Adding a Shape
You can add a shape to the active sheet by creating a shape instance and adding it to the drawing container:
var shape = new RectangleShape();
shape.Width = 300;
shape.Height = 200;
fpSpread1.ActiveSheet.DrawingContainer.AddShape(shape);
2. Attaching data to a Shape
Data can be associated with a shape using the Tag property:
shape.Tag = "abc";
3. Customizing Shape painting
To customize how a shape is rendered, create a custom shape by inheriting from RectangleShape and overriding its paint methods.
var shape = new CustomShape();
shape.Width = 300;
shape.Height = 200;
fpSpread1.ActiveSheet.DrawingContainer.AddShape(shape);
public class CustomShape : RectangleShape
{
public override void OnPaintBackground(Graphics g, Rectangle rectInput)
{
System.Drawing.Color backColor = BackColor;
bool adjusted = backColor.A == 255;
if (adjusted)
{
BackColor = System.Drawing.Color.FromArgb(128, backColor);
}
base.OnPaintBackground(g, rectInput);
if (adjusted)
{
BackColor = backColor;
}
}
protected override void PaintPicture(Graphics g, Rectangle rPict)
{
g.FillRectangle(Brushes.Green, new RectangleF(rPict.Left + 5, rPict.Top + 5, 20, 20));
}
}
4. When a Shape is pasted
You can detect when a shape is pasted using the ClipboardPasted event:
private void FpSpread1_ClipboardPasted(object sender, ClipboardPastedEventArgs e)
{
if (e.CellRange == null)
{
var shape = fpSpread1.ActiveWindowlessObject as PSShape;
}
}
5. When a Shape is moved
To track shape movement, subscribe to the PropertyChanged event:
shape.PropertyChanged += Shape_PropertyChanged;
private void Shape_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "Top":
case "Left":
break; //is moved
}
}
6. When a Shape is removed
You can handle shape removal using the ElementDeletingNotify event:
fpSpread1.ActiveSheet.DrawingContainer.ContainedObjects.ElementDeletingNotify += ContainedObjects_ElementDeletingNotify;
private void ContainedObjects_ElementDeletingNotify(object sender, Elements.ElementDeletingNotifyEventArgs e)
{
var shape = e.Element as PSShape;
}
This is how you can use Spread.NET’s legacy shape engine to create and work with shapes in your application.
Kristina Ismail