Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

how to scale graphicspath to match picturebox zoom

Posted on 2014-11-09
5
Medium Priority
?
743 Views
Last Modified: 2014-11-11
I have a picturebox on a form. I load an image into it at runtime. Then i create an array of grphicpaths to outline several shapes on the image.

But often the image needs to be stretched to fill fill the form. When this happens the pre saved graphics paths no longer line up with their corresponding shape. I am guessing that I need to scale the paths, but how do I know how much to scale them?
0
Comment
Question by:townsma
  • 3
  • 2
5 Comments
 
LVL 35

Accepted Solution

by:
Robert Schutt earned 2000 total points
ID: 40432196
I made a little test program based on some work I did for an earlier question. The code is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.Drawing.Drawing2D;

namespace EE_Q_28554079
{
    public partial class FormTestZoom : Form
    {
        GraphicsPath gp = null;
        float _offsetX = 0, _offsetY = 0, _scaleX = 1, _scaleY = 1;

        public FormTestZoom() {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e) {
            gp = new GraphicsPath();
            gp.AddLine(10, 10, 600, 200);
            gp.AddEllipse(150, 50, 200, 100);
            pictureBox1.Load(@"https://www.google.com/images/srpr/logo11w.png");

            comboBox1.Items.AddRange(Enum.GetNames(typeof(PictureBoxSizeMode)));
            comboBox1.SelectedItem = pictureBox1.SizeMode.ToString();
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e) {
            PictureBox pb = (PictureBox)sender;
            int imw = pb.Image.Width, imh = pb.Image.Height;
            //e.Graphics.DrawRectangle(Pens.Red, 0, 0, imw - 1, imh - 1); // show original location/size of image
            e.Graphics.TranslateTransform(_offsetX, _offsetY);
            e.Graphics.ScaleTransform(_scaleX, _scaleY);
            e.Graphics.DrawRectangle(Pens.Green, 0, 0, imw - 1, imh - 1); // show new location/size of image
            e.Graphics.DrawPath(Pens.Black, gp);
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) {
            ComboBox cb = (ComboBox)sender;
            pictureBox1.SizeMode = (PictureBoxSizeMode)Enum.Parse(typeof(PictureBoxSizeMode), cb.SelectedItem.ToString());
        }

        private void pictureBox1_Resize(object sender, EventArgs e) {
            SetOffsetAndScale((PictureBox)sender);
        }
        
        private void pictureBox1_SizeModeChanged(object sender, EventArgs e) {
            SetOffsetAndScale((PictureBox)sender);
        }

        private void SetOffsetAndScale(PictureBox pb) {
            int pbw = pb.ClientSize.Width, pbh = pb.ClientSize.Height, imw = pb.Image.Width, imh = pb.Image.Height;
            switch (pb.SizeMode) {
                case PictureBoxSizeMode.AutoSize:
                case PictureBoxSizeMode.Normal:
                    _offsetX = 0;
                    _offsetY = 0;
                    _scaleX = 1;
                    _scaleY = 1;
                    break;
                case PictureBoxSizeMode.CenterImage:
                    _offsetX = (float)(pbw - imw) / 2;
                    _offsetY = (float)(pbh - imh) / 2;
                    _scaleX = 1;
                    _scaleY = 1;
                    break;
                case PictureBoxSizeMode.StretchImage:
                    _offsetX = 0;
                    _offsetY = 0;
                    _scaleX = (float)pbw / imw;
                    _scaleY = (float)pbh / imh;
                    break;
                case PictureBoxSizeMode.Zoom:
                    _scaleX = (float)pbw / imw;
                    _scaleY = (float)pbh / imh;
                    if (_scaleX > _scaleY) _scaleX = _scaleY; else _scaleY = _scaleX;
                    _offsetX = (float)(pbw - _scaleX * imw) / 2;
                    _offsetY = (float)(pbh - _scaleY * imh) / 2;
                    break;
                default:
                    break;
            }
        }

    }
}

Open in new window

Important bits are: SetOffsetAndScale() which does the calculations and the Transform calls in the paint event handler which put the graphics in the right place. Note that this assumes that the graphics are originally positioned to an unscaled  image, otherwise you would need to do the opposite calculations while drawing.

Here are some screen captures:
captures
0
 
LVL 35

Expert Comment

by:Robert Schutt
ID: 40432198
Here is the designer code, in case you want to replicate the test program:
namespace EE_Q_28554079
{
    partial class FormTestZoom
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing) {
            if (disposing && (components != null)) {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent() {
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.panel1 = new System.Windows.Forms.Panel();
            this.comboBox1 = new System.Windows.Forms.ComboBox();
            this.button1 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.panel1.SuspendLayout();
            this.SuspendLayout();
            // 
            // pictureBox1
            // 
            this.pictureBox1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.pictureBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.pictureBox1.Location = new System.Drawing.Point(0, 71);
            this.pictureBox1.Name = "pictureBox1";
            this.pictureBox1.Size = new System.Drawing.Size(292, 202);
            this.pictureBox1.TabIndex = 0;
            this.pictureBox1.TabStop = false;
            this.pictureBox1.SizeModeChanged += new System.EventHandler(this.pictureBox1_SizeModeChanged);
            this.pictureBox1.Paint += new System.Windows.Forms.PaintEventHandler(this.pictureBox1_Paint);
            this.pictureBox1.Resize += new System.EventHandler(this.pictureBox1_Resize);
            // 
            // panel1
            // 
            this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
            this.panel1.Controls.Add(this.comboBox1);
            this.panel1.Controls.Add(this.button1);
            this.panel1.Controls.Add(this.textBox1);
            this.panel1.Dock = System.Windows.Forms.DockStyle.Top;
            this.panel1.Location = new System.Drawing.Point(0, 0);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(292, 71);
            this.panel1.TabIndex = 1;
            // 
            // comboBox1
            // 
            this.comboBox1.FormattingEnabled = true;
            this.comboBox1.Location = new System.Drawing.Point(10, 38);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Size = new System.Drawing.Size(121, 21);
            this.comboBox1.TabIndex = 2;
            this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
            // 
            // button1
            // 
            this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.button1.Enabled = false;
            this.button1.Location = new System.Drawing.Point(203, 10);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "Browse...";
            this.button1.UseVisualStyleBackColor = true;
            // 
            // textBox1
            // 
            this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.textBox1.Enabled = false;
            this.textBox1.Location = new System.Drawing.Point(10, 12);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(187, 20);
            this.textBox1.TabIndex = 0;
            // 
            // FormTestZoom
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(292, 273);
            this.Controls.Add(this.pictureBox1);
            this.Controls.Add(this.panel1);
            this.Name = "FormTestZoom";
            this.Text = "Q_28554079";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.panel1.ResumeLayout(false);
            this.panel1.PerformLayout();
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.PictureBox pictureBox1;
        private System.Windows.Forms.Panel panel1;
        private System.Windows.Forms.ComboBox comboBox1;
        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox1;
    }
}

Open in new window

0
 
LVL 6

Author Comment

by:townsma
ID: 40432206
Hi Robert,

Thank looks exactly what I was looking for.  I will try to pull the key parts, and embed it into my code, and see how it goes.  Will get back to you asap.

Thanks
0
 
LVL 6

Author Comment

by:townsma
ID: 40434647
Hi Robert,

You solution was just what I needed.  I have a little problem with detecting mouse clicks over the shapes, but I simply divided the point.X and point.Y by the scaling factors, and it worked.

Thanks for such a clear and concise solution.

Best regards

Mark
0
 
LVL 6

Author Closing Comment

by:townsma
ID: 40434648
Great solution and example
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Simulator games are perfect for generating sample realistic data streams, especially for learning data analysis. It is even useful for demoing offerings such as Azure stream analytics, PowerBI etc.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
We’ve all felt that sense of false security before—locking down external access to a database or component and feeling like we’ve done all we need to do to secure company data. But that feeling is fleeting. Attacks these days can happen in many w…
Suggested Courses

972 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question