#239 – Creating a Custom Shape by Overriding the Shape Class

If you need a specialized shape that you can’t use any of the Shape subclasses to draw, you can create your own custom class that inherits from Shape.

You define the shape to be drawn by overriding the Shape.DefiningGeometry property.  In the get accessor, you create and return an instance of a Geometry.  In the example below, we create a new Geometry and then use the StreamGeometryContext to draw the geometry.

    public class MyWeirdShape : Shape
    {
        protected override Geometry DefiningGeometry
        {
            get { return GenerateMyWeirdGeometry(); }
        }

        private Geometry GenerateMyWeirdGeometry()
        {
            StreamGeometry geom = new StreamGeometry();
            using (StreamGeometryContext gc = geom.Open())
            {
                // isFilled = false, isClosed = true
                gc.BeginFigure(new Point(50.0, 50.0), false, true);
                gc.ArcTo(new Point(75.0, 75.0), new Size(10.0, 20.0), 0.0, false, SweepDirection.Clockwise, true, true);
                gc.ArcTo(new Point(100.0, 100.0), new Size(10.0, 20.0), 0.0, false, SweepDirection.Clockwise, true, true);
            }

            return geom;
        }
    }

Using the new object in XAML:

	<StackPanel>
		<local:MyWeirdShape Height="150" Width="150" Stroke="Black" StrokeThickness="2"/>
	</StackPanel>

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

2 Responses to #239 – Creating a Custom Shape by Overriding the Shape Class

  1. khanh phan says:

    Thanks for your post, but how to add mouse down event to this custom shape?
    i tried adding MyWeirdShape.MouseDown += MouseDownFunction but not working

  2. orphnahk says:

    Thanks for your post. Can i ask you a question? how to add mousedown event to this custom class?
    i tried adding myWeirdShape += MouseDownFunction but not working

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: