Click here to Skip to main content
15,867,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am working on a windows application in C# where I want to select any region of a picturebox control like we can do in ms paint using tool "Free-Form Select" and latter I can edit this region as well.
I am drawing a region using code below:
C#
private void picturemap_MouseMove(object sender, MouseEventArgs e)
        {
            if (StartDrawing)
            {
                if (e.Button == MouseButtons.Left)
                {
                    paintCurrentPosition(3, Color.Red, e.X, e.Y);
                }
            }
        }
        private void paintCurrentPosition(int thickness, Color colorPen, int x, int y)
        {
            SolidBrush brush = new SolidBrush(colorPen);
            bmp = new Bitmap(picturemap.Image);
            gr = Graphics.FromImage(bmp);
            gr.FillRectangle(brush, x, y, thickness, thickness);

            picturemap.Image = bmp;
        }

Now I want to select the region what i drawn here. Any help would be greatly appreciated.
Posted
Updated 4-Mar-12 20:40pm
v2
Comments
Sergey Alexandrovich Kryukov 5-Mar-12 2:57am    
Why using PictureBox? You make your problem much more difficult than it can be. You need to use just custom control with rendering using OnPaint. PictureBox does not help you, only adds unwanted hassles, eats up performance and resources.
--SA
tanweer 5-Mar-12 3:00am    
hi SAKryukov, my requirement is to load a snapshot of a google map and then select a desired area from this image.
I dont think custom control will solve my problem.

1 solution

First off, don't do it like that.

Instead, create a GraphicsPath at class level, and add a line to it in the MouseMove handler.
C#
GraphicsPath myPath = new GraphicsPath();
...
myPath.AddLine(oldPoint, newPoint);
oldPoint = newPoint;
...

Invalidate your PictureBox, and handle the Paint event
In the Paint event, create a Region from the path and fill it:
C#
Region myRegion = new Region(myPath);
e.Graphics.FillRegion(Brushes.Red, myRegion);

You then do not damage the picture in your PictureBox, and can use the Region to reference only those parts of the image the user has marked.
 
Share this answer
 
Comments
tanweer 5-Mar-12 3:45am    
Thanks a lot for the help, when I tried the above code I am stuck with the newPoint. I set oldPoint to the position where I just clicked, what will be the newPoint when I am moving the mouse?
OriginalGriff 5-Mar-12 3:53am    
the clue is in the names:
newPoint is the place the user just clicked.
oldPoint is the place he clicked last time.
This way, he builds up a list of connected points, which form a region.

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