2014-06-20 6 views
0

나는 마우스 드래그에 직사각형 그리기 그리드 그리기 스크립트 그림 상자에 32x32 그리기 그리기 그리드에 사각형을 스냅인 할 노력하고 있어요 사각형 안에 쐈어.격자 그리기 그리드에 그리드

저는 스크린 샷 비트와 격자 그리기 비트를 가지고 있습니다.

_selection = new Rectangle(SnapToGrid(e.Location), new Size()); 

그리고이 같은 MouseMove 이벤트의 폭을 조정할 수 있습니다

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 as Bitmap; 

    // Check if it is a bitmap: 
    if (bmp == null) 
     throw new ArgumentException("No valid bitmap"); 

    // Crop the image: 
    Bitmap cropBmp = bmp.Clone(selection, bmp.PixelFormat); 

    // Release the resources: 
    image.Dispose(); 

    return 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 to the picturebox: 
     //pictureBox1.Image = img; 

     _selecting = false; 
    } 
    else 
     _selecting = false; 
} 

private void pictureBox1_Paint(object sender, PaintEventArgs e) 
{ 
    if (_selecting) 
    { 
     // Draw a rectangle displaying the current selection 
     Pen pen = Pens.GreenYellow; 
     e.Graphics.DrawRectangle(pen, _selection); 
    } 

    Graphics g = e.Graphics; 
    int numOfCells = amount; 
    Pen p = new Pen(Color.LightGray); 

    for (int y = 0; y < numOfCells; ++y) 
    { 
     g.DrawLine(p, 0, y * ysize, numOfCells * ysize, y * ysize); 
    } 

    for (int x = 0; x < numOfCells; ++x) 
    { 
     g.DrawLine(p, x * xsize, 0, x * xsize, numOfCells * xsize); 
    } 
} 
+1

그리드 코드에 스냅합니다. 어떻게 작동할까요? –

+0

창을 "찍을 수있는"추상 아이디어가 어떻게 작동하는지 묻는 중입니까? 나는'snapPadDist'를 선언 할 것이고 드래그 할 때 마우스의 값이 타겟 사각형의'snapPadDist' 내에 있다면, 타겟 사각형과 같은 크기의 사각형을 그려 볼 수 있습니다. – AnotherUser

답변

2

우선은

private Point SnapToGrid(Point p) 
{ 
    double x = Math.Round((double)p.X/xsize) * xsize; 
    double y = Math.Round((double)p.Y/ysize) * ysize; 
    return new Point((int)x, (int)y); 
} 

는 그런 다음 MouseDown이 같은 선택을 초기화 할 수있는 스냅 방법을 선언합니다 :

Point dest = SnapToGrid(e.Location); 
_selection.Width = dest.X - _selection.X; 
_selection.Height = dest.Y - _selection.Y; 
+0

완벽하게 작동했습니다! 고맙습니다 – Houlahan

관련 문제