如何确保图形绘制在正确的位置?我有一个Windows窗体项目,用户可以在pictureBox(位于面板顶部)的Image上绘制线条。当图片框处于默认缩放状态时,线条会正确绘制,并且它们可以正确响应图像周围的衣衫agged。但是,当我尝试在放大/缩小时在图像上绘制时,线条的位置会偏移(缩小时向上和向左偏移,放大时向下和向右偏移)。 pictureBox和面板固定在所有四个侧面上,并且未固定。我尝试使用TranslateTransform(dx,dy)方法,但是没有用。我也尝试摆脱CenterBox()方法。我该如何进行?
以下是缩放代码:
private void trackBar1_Scroll(object sender, EventArgs e) // zoom scale
{
zoom = (float)(0.25 + 0.25 * (trackBar1.Value - 1));
if (trackBar1.Value > 0)
{
pictureBox1.Image = PictureBoxZoom(imgOriginal, new Size(trackBar1.Value, trackBar1.Value));
}
}
public Image PictureBoxZoom(Image img, Size size) //creates zoomed in clone of user image
{
sizeNewx = (Int32) (img.Width * zoom);
sizeNewy = (Int32) (img.Height * zoom);
Bitmap bm = new Bitmap(img, sizeNewx,sizeNewy);
Graphics grap = Graphics.FromImage(bm);
grap.InterpolationMode = InterpolationMode.HighQualityBicubic;
CenterBox(pictureBox1, bm);
return bm;
}
private void CenterBox(PictureBox picBox, Bitmap pic)
{
picBox.Image = pic;
picBox.Location = new Point((picBox.Parent.ClientSize.Width / 2) - (pic.Width / 2),
(picBox.Parent.ClientSize.Height / 2) - (pic.Height / 2));
picBox.Refresh();
}
以下是绘制和缩放图形的方式:
private Stack<Line> lines = new Stack<Line>();
private void pictureBox1_MouseDown(object sender, MouseEventArgs e) //click in box
{
var mouseEventArgs2 = e as MouseEventArgs;
if (e.Button == MouseButtons.Left)
{
lines.Push(new Line { Start = mouseEventArgs2.Location });
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (lines.Count > 0 && e.Button == System.Windows.Forms.MouseButtons.Left)
{
lines.Peek().End = e.Location;
pictureBox1.Invalidate();
}
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.ScaleTransform(zoom, zoom);
foreach (var line in lines)
{
Pen magenta = new Pen(Color.Magenta, 2);
e.Graphics.DrawLine(magenta, line.Start, line.End);
}
}
答案 0 :(得分:1)
确定发现了问题。问题在于,您在mouse move
和mouse end
中获得的点基本上是缩放的,导致图像缩放,然后在绘画中再次缩放它们。因此,您需要在涂漆之前取消缩放比例:
private void pictureBox1_MouseDown(object sender, MouseEventArgs e) //click in box
{
var mouseEventArgs2 = e as MouseEventArgs;
if (e.Button == MouseButtons.Left)
{
Point[] pnts = new Point[ 1 ];
Matrix scaleMatrix = new Matrix( 1 / zoom, 0, 0, 1 / zoom, 0, 0 ); //un scale
pnts[0]= mouseEventArgs2.Location;
scaleMatrix.TransformPoints( pnts );
lines.Push(new Line { Start = pnts[0] });
}
}
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (lines.Count > 0 && e.Button == System.Windows.Forms.MouseButtons.Left)
{
Point[] pnts = new Point[ 1 ];
Matrix scaleMatrix = new Matrix( 1 / zoom, 0, 0, 1 / zoom, 0, 0 ); //un scale
pnts[0]= e.Location;
scaleMatrix.TransformPoints( pnts );
lines.Peek().End = pnts[0];
pictureBox1.Invalidate();
}
}