2010-07-03 112 views
0

我畫了一個矩形。屏幕上顯示的是水平滾動條。現在我想放大矩形。在縮放矩形的高度增加時,位置向上移動,水平滾動條向上移動。這個怎麼做?我寫這一段代碼:如何縮放矩形?

rect = new Rectangle(rect.Location.X, this.Height - rect.Height,rect.Width, Convert.ToInt32(rect.Size.Height * zoom)); 
g.FillRectangle(brush, rect); 

這適用於即矩形上移,但高度不會增加矩形的位置。幫幫我!

回答

1

如果您只是想要圍繞矩形的中心縮放矩形,則需要增加矩形的寬度和高度,並從該位置減去一半的增量。

這不是測試,但應該給你的總體思路

double newHeight = oldHeight * scale; 
double deltaY = (newHeight - oldHeight) * 0.5; 

rect = new Rectangle(
    rect.Location.X, (int)(rect.Location.Y - deltaY), 
    rect.Width, (int)newHeight); 

可能是一個更好的替代方法是看看使用Graphics.ScaleTransform

0

只是txtZoom添加到您的形式:

using System.Drawing; 
using System.Drawing.Drawing2D; 
using System.Windows.Forms; 

namespace WindowsFormsApplication1 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
      this.txtZoom.Text = "1"; 
      this.txtZoom.KeyDown += new KeyEventHandler(txtZoom_KeyDown); 
      this.txtZoom_KeyDown(txtZoom, new KeyEventArgs(Keys.Enter)); 
     } 

     void txtZoom_KeyDown(object sender, KeyEventArgs e) 
     { 
      if (e.KeyData == Keys.Enter) 
      { 
       this.Zoom = int.Parse(txtZoom.Text); 
       this.Invalidate(); 
      } 
     } 

     public int Zoom { get; set; } 

     protected override void OnPaint(PaintEventArgs e) 
     { 
      GraphicsPath path = new GraphicsPath(); 
      path.AddRectangle(new Rectangle(10, 10, 100, 100)); 

      Matrix m = new Matrix(); 
      m.Scale(Zoom, Zoom); 

      path.Transform(m); 
      this.AutoScrollMinSize = Size.Round(path.GetBounds().Size); 

      e.Graphics.FillPath(Brushes.Black, path); 
     } 
    } 
}