Monday, 15 April 2013

c# - Snap drawn rectangle to grid -



c# - Snap drawn rectangle to grid -

i have below draws rectangle on mouse drag , grid drawing script draws 32x32 grid on image box i'm trying snap rectangle grid screen shot within rectangle.

i've got screen shot bit , drawing of rectangle not snapping grid bit working.

private bool _selecting; private rectangle _selection; private void piccanvas_mousedown(object sender, system.windows.forms.mouseeventargs e) { if (e.button == mousebuttons.left) { _selecting = true; _selection = new rectangle(new point(e.x, e.y), new size()); } } private void piccanvas_mousemove(object sender, system.windows.forms.mouseeventargs e) { if (_selecting) { _selection.width = e.x - _selection.x; _selection.height = e.y - _selection.y; picturebox1.refresh(); } } public image crop(image image, rectangle selection) { bitmap bmp = image bitmap; // check if bitmap: if (bmp == null) throw new argumentexception("no valid bitmap"); // crop image: bitmap cropbmp = bmp.clone(selection, bmp.pixelformat); // release resources: image.dispose(); homecoming cropbmp; } private void piccanvas_mouseup(object sender, system.windows.forms.mouseeventargs e) { if (e.button == mousebuttons.left && _selecting && _selection.size != new size()) { // create cropped image: //image img = crop(picturebox1.image, _selection); // fit image picturebox: //picturebox1.image = img; _selecting = false; } else _selecting = false; } private void picturebox1_paint(object sender, painteventargs e) { if (_selecting) { // draw rectangle displaying current selection pen pen = pens.greenyellow; e.graphics.drawrectangle(pen, _selection); } graphics g = e.graphics; int numofcells = amount; pen p = new pen(color.lightgray); (int y = 0; y < numofcells; ++y) { g.drawline(p, 0, y * ysize, numofcells * ysize, y * ysize); } (int x = 0; x < numofcells; ++x) { g.drawline(p, x * xsize, 0, x * xsize, numofcells * xsize); } }

first declare snapping method

private point snaptogrid(point p) { double x = math.round((double)p.x / xsize) * xsize; double y = math.round((double)p.y / ysize) * ysize; homecoming new point((int)x, (int)y); }

then can initialize selection in mousedown:

_selection = new rectangle(snaptogrid(e.location), new size());

and can adjust width in mousemove this:

point dest = snaptogrid(e.location); _selection.width = dest.x - _selection.x; _selection.height = dest.y - _selection.y;

c# winforms grid picturebox

No comments:

Post a Comment