getframe(), rectangle specified in normalized coordinates instead of pixel coordinates

10 views (last 30 days)
S.
S. on 25 Mar 2022
Commented: Simon Chan on 29 Mar 2022
I want to use the getframe() option to make a snapchat of a part of my figure. However, the documentation says that getframe(__, rect), the rectangle coordinates are in pixels. However, to ensure that I will get the same snapshot on another computer, how can I give rect in normalized coordinates?
rect = [65 385 720 255];
f = getframe(h.f, rect); %h.f is the parent container
f = frame2im(f);

Answers (1)

Simon Chan
Simon Chan on 25 Mar 2022
Try the following workaround
f = figure;
f.Units = 'normalize';
f.Position = [0.25 0.25 0.5 0.5]; % Location of the figure on the screen
ax = gca;
ax.Units = 'pixels';
plot(1:10,1:10);
ti = ax.TightInset;
pos = ax.Position;
rect = [-ti(1), -ti(2), pos(3)+ti(1)+ti(3), pos(4)+ti(2)+ti(4)];
F = getframe(ax,rect);
  2 Comments
Simon Chan
Simon Chan on 29 Mar 2022
The code should work as follows without any error message.
However, I tested again and found that the TightInset properties is read only and hence the figures saved by the above method may looks a little bit different.
The workaround is to assign a specific axis position for the figure so that the size of the figures saved from any screen resolution should be the same.
f = figure;
f.Units = 'normalize';
f.Position = [0.25 0.25 0.5 0.5]; % Location of the figure on the screen
ax = gca;
ax.Units = 'pixels'; % Set units to pixels
plot(ax,1:10,1:10);
ti = ax.TightInset;
ax.Position = [100 50 500 300]; % This should be specific
pos = ax.Position;
rect = [-ti(1), -ti(2), pos(3)+ti(1)+ti(3), pos(4)+ti(2)+ti(4)];
F = getframe(ax,rect);
ax.Position
ans = 1×4
100 50 500 300
% imwrite(F.cdata,'test1.png') % save the figure

Sign in to comment.

Categories

Community Treasure Hunt

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

Start Hunting!