Use the mouse wheel to scale images while cropping them to a desired aspect ratio in C#

[example]

This example adds mouse wheel support to the example Crop scaled images to a desired aspect ratio in C#.

Some social media platforms work best with a 4:3 aspect ratio, so I use that example almost every day to crop images to a particular aspect ratio before posting them. If an image won’t work with that aspect ratio, I sometimes crop them to a 1:1 (square) aspect ratio. You can see some of these images on Facebook, Google business, and The Enchanted Oven.

When I use MS Paint, I often use the mouse wheel to zoom in and out. It’s so easy that I decided to add similar mouse wheel support to the cropping example.

Supporting the mouse wheel isn’t very hard once you know the trick, and there is a trick! The Visual Studio Properties window does not know about the MouseWheel event, so you need to register to catch that event at run time. The following code shows how this example does that.

private void Form1_Load(object sender, EventArgs e)
{
    ...
    // Prepare to use the mouse wheel.
    this.MouseWheel += Form_MouseWheel;
}

After performing setup chores used by the previous example, this program registers the Form_MouseWheel method to catch the form’s MouseWheel event handler.

I’ll show you that event handler shortly. First I want to show you how the program changes the image’s scale.

SetScale

The previous version of this program lets you use the Scale menu’s items to select one of the scale factors 100%, 75%, 66%, 50%, 25%, or 15%. That example made the selection right in the menu items’ shared event handler. The new example needs to allow the Form_MouseWheel event handler to also set the scale factor, so I rearranged the code a bit. Now the program uses the following method to set the scale.

// Set the appropriate scale for this menu item.
private void SetScale(ToolStripMenuItem menu_item)
{
    // Get the scale factor.
    string scale_text = menu_item.Text.Replace("&", "").Replace("%", "");
    ImageScale = float.Parse(scale_text) / 100f;
    ShowScaledImage();

    // Display the new scale.
    mnuScale.Text = "Scale (" + menu_item.Text.Replace("&", "") + ")";

    // Check the selected menu item.
    foreach (ToolStripMenuItem item in mnuScale.DropDownItems)
    {
        item.Checked = (item == menu_item);
    }
}

This method takes as a parameter the menu item that represents the new scale. It takes the item’s caption, removes any & or % characters that it contains, parses the result, and divides by 100 to get the scale as a floating point number. For example, that transforms the caption &25% into the value 0.25.

The code then calls the ShowScaledImage method to redisplay the image and selection rectangle at the new scale.

The method then displays the new scale factor in the Scale menu’s caption as in “Scale (25%).” (See the picture at the top of this post.)

Finally, the method loops through the Scale menu’s dropdown items, checks the item that came in as the method’s parameter, and unchecks the others.

When you select one of the Scale menu’s items, the following event handler executes.

private void mnuScale_Click(object sender, EventArgs e)
{
    // Get the scale factor.
    SetScale(sender as ToolStripMenuItem);
}

This method simply calls the new SetScale method, passing it the menu item that you selected.

Form_MouseWheel

The following event handler executes when you use the mouse wheel.

// Respond to the mouse wheel.
private void Form_MouseWheel(object sender, MouseEventArgs e)
{
    if (OriginalImage == null) return;

    // Find the current scale.
    int int_scale = (int)(ImageScale * 100);

    // Find the index of the corresponding menu item.
    ToolStripMenuItem[] menu_items =
    {
        mnuScale100,
        mnuScale75,
        mnuScale66,
        mnuScale50,
        mnuScale25,
        mnuScale15,
    };
    List scales = new List()
        { 100, 75, 66, 50, 25, 15 };
    int index = scales.IndexOf(int_scale);

    // If we're zooming out, move to a smaller scale.
    // Else move to a larger scale.
    if (e.Delta < 0) index++;
    else index--;

    // Select the new scale menu item.
    if ((index >= 0) && (index < menu_items.Length))
    {
        SetScale(menu_items[index]);
    }
}

This code first checks to see if an image is loaded and returns if one is not. Next the method multiplies the scale factor, which is something like 0.25, by 100 to get a value like 25.

The method then creates an array holding the Scale menu’s items. It makes a corresponding list of the items’ scale factors.

The code then uses the scales list’s IndexOf method to get the index of the current scale factor. That index is also the index of the currently selected Scale menu item.

If the event handler’s e.Delta parameter is less than zero, then you have moved the mouse wheel down (toward you). In that case, the code increments index to move to a smaller scale factor in the menu_items array. If e.Delta parameter is greater than zero, the code decrements index to move to a larger scale factor.

If the new index has not moved out of the menu_items array, the code calls the SetScale method described earlier, passing it the menu item that represents the new scale factor. The SetScale method then updates the scale factor, displays the image at the new scale, and shows the scale in the Scale menu’s caption.

Conclusion

Using the mouse wheel isn’t hard. The only trick is knowing that you need to install its event handler at run time because the Properties window doesn’t know about it.

See the previous example and download the example to see additional details.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in drawing, graphics, image processing and tagged , , , , , , , , , . Bookmark the permalink.

2 Responses to Use the mouse wheel to scale images while cropping them to a desired aspect ratio in C#

  1. Creola Funk says:

    The technique at that point makes an exhibit holding the Scale menu’s things. It makes a relating rundown of the things’ scale factors.

    • RodStephens says:

      Yes. This example only allows the scale factors in the Scale menu. That’s the way MS Paint does it and it seemed appropriate.

      You could change that if you like. For example, you could make the wheel increase or decrease the scale factor by 10% for each click. You couldn’t show the scale factor by selecting an item in the Scale menu, but I think that would be a reasonable approach.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.