Tip

Draw a bounding rectangle during selection

How many times have you seen a UI like this in a drawing program?

 That selection rectangle is sometimes called a bounding rectangle. Its purpose is to provide feedback to the designer during the selection process. It's a convenient way to show what is currently selected before applying the next operation. You may have seen it rendered differently, another common look is to have transparent fill and a dotted outline.

In the example above, I selected the kids eyes with the selection rectangle and then used the crop tool to trim the source down to a smaller image.

Creating similar UI in WPF
If you want to draw a selection tool like our example you have to build your own. Fortunately it's not that hard to create the bounding rectangle.

I'll start by creating a basic layout for our application.

Flipping the rectangle
To draw the rectangle we need a starting point and width and height value. The starting point is easy to get, I can capture it in the MouseLeftButtonDown event.

 The next part is little a trickier. Once the user clicks and starts dragging the mouse they can drag in four general directions from the starting point; NE, SE, SW and NW. I need to know the upper left hand corner of the rectangle in order to draw it accurately.

If the user is drawing in the NW direction then the current mouse position is the upper left position for the rectangle. If the user drags in the SE direction, then the anchor point is the upper-left.

 Here's the logic that determines the correct positions and sizes for the rectangle. It also makes the rectangle visible.

Clean up
Finally, I have a few lines of code to cleanup when the mouse button is released or the mouse leaves the back canvas.

 This is the final results.


This was first published in September 2010

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.