如何缩放矩形?

时间:2010-07-03 12:23:45

标签: c# winforms

我画了一个矩形。它是屏幕上的水平滚动条。现在我想缩放矩形。在缩放时,矩形的高度增加,位置向上移动,水平滚动条向上移动。这该怎么做?我正在写这段代码:

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

这适用于矩形的位置,矩形向上移动但高度不会增加。救命啊!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);
        }
    }
}