Click here to Skip to main content
15,936,802 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello,

I have a PictureBox and I want to draw dynamic rectangles on tip of the image that can be resized (if necessary). I will not be a part of the image rather it will act as a layer on top of the image.

None of the codes online seem to help. Please help.

Regards
Aman Chaurasia

What I have tried:

I tried drawing under MouseDown, MouseMove, MouseUp and Paint events but none seem to have worked.
Posted
Updated 1-May-18 0:15am

1 solution

OK, I'm assuming you're in the world of WinForms here.

What you really are doing is developing a custom control - a specialization of a picture box which also supports the overlay of shapes. First thing to note is that any drawing should only be done in the Paint method, certainly not in mouse movement events.

The way it works is all drawing goes in the paint event handler, and when drawing is needed you Invalidate() the area concerned, this will invoke a new paint, and if you do it well your paint method only need to draw in the area which needs refreshing.

So, start by deriving a new class from PictureBox, this is going to be the 'specialization' of PictureBox because we're extending it's functionality. The first thing to do is override the OnPaint method, make sure you call the base.() method, as this will draw the picture, but then we can add our own drawing code to go over the top. Here's an example that puts a black square over the picture:

public class Box : PictureBox
{
    protected override void OnPaint(PaintEventArgs pe)
    {
        // let the default draw the image
        base.OnPaint(pe);

        pe.Graphics.FillRectangle(System.Drawing.Brushes.Black, new System.Drawing.Rectangle(0, 0, Width - 100, Height - 100));
    }
}



That's a starting point. Alter your designer code to create a new Box rather than a new PictureBox.

From here, it's just a case of adding the logic to keep track of your rectangles, and do the dragging - so you'll need to intercept the mouse events, determine when tracking occurs (mouse button held down), change the dimension of the choice rectangle and issue Invalidate()s. A good control should respond to the keyboard as well.

Control development is fiddly and hard to get perfect, but its just a case of keeping going and nudging it in the right direction when you get familiar with the calls and callbacks you need.
 
Share this answer
 
Comments
Primo Chalice 1-May-18 6:24am    
Thank you so much. I think this will help :). I will get back to you once I am done :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900