2013-10-08 112 views
0

我画一条线在PictureBox这样:画线的PictureBox和重绘在变焦

horizontalstart = new Point(0, e.Y); //Start point of Horizontal line. 
horizontalend = new Point(picbox_mpr.Width, e.Y); //End point of Horizontal line. 
verticalstart = new Point(e.X, 0); //Start point of Vertical line 
verticalend = new Point(e.X, picbox_mpr.Height); //End point of Vertical line. 

然后在漆事件我这样做:

e.Graphics.DrawLine(redline, horizontalstart, horizontalend); //Draw Horizontal line. 
e.Graphics.DrawLine(redline, verticalstart, verticalend); //Draw Vertical line. 

很简单,现在,我的形象可以放大,这里是我奋斗的地方..

即使我放大图像,该如何保持画出的同一点?

+0

一个好办法,简化代码是寻找到图形的转换。如果你不擅长数学,可能有点难以理解,但一旦你掌握了基础知识,缩放,移动和缩放的代码变得非常易读和清晰。 – korhner

回答

1

不是存储绝对整数坐标,而是存储表示该坐标相对于图像宽度/高度的“百分比”的十进制值。所以如果X值为10,宽度为100,则存储0.1。假设图像被缩放,现在宽度为300。现在0.1将转换为0.1 * 300 = 30.您可以将Point()中的“百分比”X,Y对存储为Point()。

这里有一个简单的例子玩:

public partial class Form1 : Form 
{ 

    private List<Tuple<PointF, PointF>> Points = new List<Tuple<PointF, PointF>>(); 

    public Form1() 
    { 
     InitializeComponent(); 
     this.Shown += new EventHandler(Form1_Shown); 

     this.pictureBox1.BackColor = Color.Red; 
     this.pictureBox1.SizeChanged += new EventHandler(pictureBox1_SizeChanged); 
     this.pictureBox1.Paint += new PaintEventHandler(pictureBox1_Paint); 
    } 

    void Form1_Shown(object sender, EventArgs e) 
    { 
     // convert absolute points: 
     Point ptStart = new Point(100, 25); 
     Point ptEnd = new Point(300, 75); 

     // to percentages: 
     PointF ptFstart = new PointF((float)ptStart.X/(float)pictureBox1.Width, (float)ptStart.Y/(float)pictureBox1.Height); 
     PointF ptFend = new PointF((float)ptEnd.X/(float)pictureBox1.Width, (float)ptEnd.Y/(float)pictureBox1.Height); 

     // add the percentage point to our list: 
     Points.Add(new Tuple<PointF, PointF>(ptFstart, ptFend)); 
     pictureBox1.Refresh(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     // increase the size of the picturebox 
     // watch how the line(s) change with the changed picturebox 
     pictureBox1.Size = new Size(pictureBox1.Width + 50, pictureBox1.Height + 50); 
    } 

    void pictureBox1_SizeChanged(object sender, EventArgs e) 
    { 
     pictureBox1.Refresh(); 
    } 

    void pictureBox1_Paint(object sender, PaintEventArgs e) 
    { 
     foreach (Tuple<PointF, PointF> tup in Points) 
     { 
      // convert the percentages back to absolute coord based on the current size: 
      Point ptStart = new Point((int)(tup.Item1.X * pictureBox1.Width), (int)(tup.Item1.Y * pictureBox1.Height)); 
      Point ptEnd = new Point((int)(tup.Item2.X * pictureBox1.Width), (int)(tup.Item2.Y * pictureBox1.Height)); 
      e.Graphics.DrawLine(Pens.Black, ptStart, ptEnd); 
     } 
    } 

} 
+0

你可以发表一个例子吗?谢谢! – Matimont