在缩放的图片上获取鼠标位置

时间:2015-02-22 14:53:43

标签: c# bitmap position mouse picturebox

我正在创建一个截图制作者/上传者,一切都很好但现在我想整合像油漆这样的东西。所以首先我要创建铅笔功能。但是开始出现我可以画的问题:D而不是鼠标的位置。他采取其他立场然后我的光标?

所以问题是: 锄头可以将鼠标放在缩放的图片框上吗?

我的代码:

private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
    {
        if (draw && pencil)
        {
            Graphics panel = Graphics.FromImage(ScreenShot);

            Pen pen = new Pen(Color.Black, 14);

            pen.EndCap = LineCap.Round;
            pen.StartCap = LineCap.Round;

            panel.DrawLine(pen, pX, pY, e.X, e.Y);

            pictureBox1.CreateGraphics().DrawImage(ScreenShot, pictureBox1.Width, pictureBox1.Height);

            pictureBox1.Invalidate();
        }
        Point p = pictureBox1.PointToClient(Cursor.Position);

        pX = p.X;
        pY = p.Y;
    }

2 个答案:

答案 0 :(得分:0)

在缩放图像上使用鼠标时,报告的像素是缩放的坐标。所以我们需要得到真实像素..

以某种方式设置事物后......

float pbZoom = 3f;  // the factor by which the PictureBox is zoomed in or out

pictureBox.SizeMode = PictureBoxSizeMode.Zoom;
pictureBox.ClientSize = new Size((int)(pictureBox.Image.Width * pbZoom),
         (int)(pictureBox.Image.Height * pbZoom));

pictureBox.Paint     += pictureBox_Paint;
pictureBox.MouseDown += pictureBox_MouseDown;
pictureBox.MouseMove += pictureBox_MouseMove;
pictureBox.MouseUp   += pictureBox_MouseUp;

..您可以编写要在缩放图像上绘制的事件。

首先是一个辅助函数来撤消一个点的缩放:

PointF unZoomed(PointF pt) { return new PointF(pt.X / pbZoom, pt.Y / pbZoom );}

为简单起见,我们在课堂上保留一些东西:

PointF mDown    = PointF.Empty;   // mouse down point
PointF mCurrent = PointF.Empty;   // current mouse location

我们通过计算unzoomed e.Location开始每个鼠标事件。

我们的测试在表面上绘制直线,移动的红线,直到您释放鼠标。然后该行以绿色绘制到图像中。

MouseDown只是存储起点,unzoomed:

void pictureBox_MouseDown(object sender, MouseEventArgs e)
{
    mDown = unZoomed(e.Location);
}

MouseMove我们存储当前点并触发Paint事件:

void pictureBox_MouseMove(object sender, MouseEventArgs e)
{
    if (e.Button == System.Windows.Forms.MouseButtons.None) return;

    PointF e_ = unZoomed(e.Location);
    mCurrent = e_;
    pictureBox.Invalidate();
}

MouseUp中,我们将线条绘制到Image的{​​{1}},更改其像素;然后我们设置PictureBox并重置点数:

Image

要绘制到控制界面,我们使用void pictureBox_MouseUp(object sender, MouseEventArgs e) { Bitmap bmp = (Bitmap) pictureBox.Image; using (Graphics G = Graphics.FromImage(bmp)) { G.SmoothingMode = SmoothingMode.HighQuality; G.DrawLine(Pens.Green, mDown, mCurrent); } mDown = PointF.Empty; mCurrent = PointF.Empty; pictureBox.Image = bmp; } 事件。要绘制缩放比例,我们使用Paint ..:

Matrix

答案 1 :(得分:0)

我还处理缩放图像。我只是使用此代码,即可正常工作。因此,您可以在放大/缩小之前与位图(原始图像)进行比较。

private void pbInput_MouseMove(object sender, MouseEventArgs e) { 
    if (pbInput.Image == null) {
        mouseY.Text = "";
        mouseX.Text = "";
    }

    else {
        Bitmap b = new Bitmap(pbInput.Image);
        int x = b.Width * e.X / pbInput.Width;
        int y = b.Height * e.Y / pbInput.Height;

        mouseX.Text = x.ToString();
        mouseY.Text = y.ToString();
    }
}