tags:

views:

55

answers:

2

I have drawn a rectangle. It is undreneath a horizontal scroll bar on screen. Now i want to zoom the rectangle. On zooming the height of rectangle increases, the location shifts up and horizontal scroll bar moves up. How to do this? I am writing this piece of code:

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

This works for the location of the rectangle that is the rectangle shifts up but the height doesn't increase. Help!

+1  A: 

If you simply want to scale the rectangle around the center of the rectangle then you need to increase the width and height of the rectangle and subtract half the increase from the location.

This is not tested, but should give you the general idea

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);

Possibly a better alternative would be to look at using Graphics.ScaleTransform.

Chris Taylor
A: 

Just add a txtZoom to your form:

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);
        }
    }
}
serhio