getframe() captures the wrong part of the screen when figure is maximized (R2021b)
    7 views (last 30 days)
  
       Show older comments
    
I want to save full-screen images (or as large as I can make them) containing only what's plotted in the axes. To do this, I create a maximized figure and then use getframe(ax) to capture the axes. This used to work in previous versions of Matlab but I haven't tried it with any version between R2015b and R2021b. 
Here is a minimum working example:
% Make dummy data to plot
x = linspace(0, 2*pi, 20);
y = sin(x);
% Make figure and axes:
f1 = figure(1);
f1.WindowState = 'maximized';
ax1 = axes('Parent', f1);
plot(ax1, x, y)
% Save an image of what's on the axes:
frame = getframe(ax1);
imwrite(frame.cdata, 'example.png')
Attached is the image that gets saved as a result. It is improperly cropped around the bottom left part of the axes and contains parts outside the axes. I have also tried adding a pause(1.0) command before calling getframe() but it produces the same image. The behavior is the same if I call getframe() without arguments and let it choose the current axes. However, when the figure is not maximized, the saved image does indeed contain only what is in the axes. 
How can I capture the axes properly when the parent figure is maximized?
2 Comments
Answers (1)
  Image Analyst
      
      
 on 15 Nov 2021
        This works fine for me:
% Make dummy data to plot
x = linspace(0, 2*pi, 20);
y = sin(x);
% Make figure and axes:
f1 = figure(1);
f1.WindowState = 'maximized';
ax1 = axes('Parent', f1);
plot(ax1, x, y)
drawnow;
% Save an image of what's on the axes:
exportgraphics(ax1, 'example.png')
Your original code only saved stuff inside the box, not the tick labels, like this code does.
8 Comments
See Also
Categories
				Find more on Printing and Saving in Help Center and File Exchange
			
	Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!


