Search code examples
matlabresizepositionfigureaspect-ratio

Keep aspect ratio figure


How to resize an image keeping the ratio between width and height when the figure is resized (F3/F4 should keep constant)?

f=figure();
F1=300;F2=300;F3=600;F4=300;
f.Position=[F1 F2 F3 F4];

Solution

  • You can use the following feedback function to achieve what you want:

    set(f,'SizeChangedFcn',@(src, callbackdata) onSizeChanged(src, F3, F4));
    
    function onSizeChanged(src, F3, F4)
       pos = src.Position;
       scale = (pos(3)/F3 + pos(4)/F4)/2; % estimate the desired scale factor
       % scale = min(pos(3)/F3, pos(4)/F4); % alternative
       pos(3) = scale*F3;
       pos(4) = scale*F4;
       src.Position = pos;
    end
    

    An alternative may be to use pbaspect, but this will change the aspect ratio of the plot, not the window itself.