2013-10-08 45 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