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

조회 수: 7 (최근 30일)
Nathan
Nathan 2021년 11월 14일
댓글: Image Analyst 2021년 11월 16일
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
Walter Roberson
Walter Roberson 2021년 11월 14일
Have you experimented with exportgraphics() ?
Nathan
Nathan 2021년 11월 15일
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');

댓글을 달려면 로그인하십시오.

답변 (1개)

Image Analyst
Image Analyst 2021년 11월 15일
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
Nathan
Nathan 2021년 11월 16일
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?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Printing and Saving에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by