getframe() captures the wrong part of the screen when figure is maximized (R2021b)

7 views (last 30 days)
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
Nathan
Nathan on 15 Nov 2021
exportgraphics() seems to work much better. Thanks for the suggestion!
Just to document what I'm changing: exportgraphics() captures the axis tick labels by default, but I discovered I can turn them off by setting:
ax1.XTick = [];
ax1.YTick = [];
I don't need a grid, but if a grid is desired in the plot, one could substitute these commands instead:
ax1.XTickLabels = [];
ax1.YTickLabels = [];
Then I create the image with:
exportgraphics(ax1, 'example2.png');

Sign in to comment.

Answers (1)

Image Analyst
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
Nathan
Nathan on 16 Nov 2021
It looks like this should work but I haven't tried it yet. Maybe I'll tinker tomorrow:
I'm pretty sure the strange cropping from getframe() is not the intended behavior but I'm not sure if I've done something wrong or if it's a bug. Should I submit a bug report?

Sign in to comment.

Categories

Find more on Printing and Saving in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!