Search code examples
c#.netimagepicturebox

How to centre picture box


I am trying to use this plugin for C#, which works great. However I am having difficulty getting the image to center when zooming in. By default, whenever zooming, the picture box focuses on the top left corner. I would like it to focus on the centre.

Any idea? I have searched far and wide and cannot find an example which does this within this plugin.


Solution

  • Ok, this getting complicated so I will write complete answer:

    The plugin is not open in the way You can hook on the zooming events. Actualy thing You can do (as You have open sources) is to "hack" inside - change the source code and adjust to Your needs.

    Options:

    1. Change inner implementation:

    Get to file ScalablePictureBoxImp.cs , find method ScalePictureBoxToFit(), and add the codes after lines:

    //some previous code
    this.pictureBox.Left = left;
    this.pictureBox.Top = top;
    this.AutoScroll = true;
    
    // add this line under:
    this.AutoScrollPosition = new Point(this.Width / 2, this.Height / 2);
    

    Now You can simply use the component as before, and it will do all the things just with resizing them on middle (it possibly need some more math to fit the screen properly).

    2. Change outer implementation:

    Author is ussing wrapper for the inner implementation, where he is hooking on the events and You are just using the wrapped object (it is like pressing the buttons on a mouse instead of connecting 1 wire with some other).

    In file ScalablePictureBox.cs edit the Constructor and add following implementation:

    public ScalablePictureBox()
    {
        //some code ...
    
    
        this.pictureTracker.ScrollPictureEvent += new PictureTracker.ScrollPictureEventHandler(this.scalablePictureBoxImp.OnScrollPictureEvent);
        this.pictureTracker.PictureTrackerClosed += new PictureTracker.PictureTrackerClosedHandler(this.pictureTracker_PictureTrackerClosed);
    
        //Enter the line below to hook on event
         this.scalablePictureBoxImp.ZoomRateChangedEvent += ScalablePictureBoxImp_ZoomRateChangedEvent;
    }
    

    Now You have hooked on the event of zooming, and You just need to adjust the scrolling:

    private void ScalablePictureBoxImp_ZoomRateChangedEvent(int zoomRate, bool isFullPictureShown)
    {
        this.scalablePictureBoxImp.AutoScrollPosition = new Point(this.Width / 2, this.Height / 2);
    }
    

    Inner implementation of the ScalablePictureBox is invoking event ZoomRateChangedEvent -> Once this zoom change, You will get the size of a window and move the scroll buttons to the middle position. This can be adjusted in any way You requiring.

    I believe, originaly autor wanted to write ScalablePictureBoxImp only and the wrapper was added just for test/simply case purpose. It is completely up to You if You write it all Yourself or adjust -> Correct way should be using the outer implementation then.