Group multiple lines to one "object" and be able to "toggle" on or off

34 views (last 30 days)
Hi, I have this functioj that draws a grid on an image
function drawGrid(RowSize,ColSize,IM,ax)
% Rowsize=512
% Colsize=256
[height,width]=size(IM);
nRows=floor(height/RowSize);
nCols=floor(width/ColSize);
hold(ax,"on");
for i=1:nRows %plot Col Lines
plot(ax,[1 width],[i*RowSize i*RowSize],'r','LineWidth',0.2)
end
for i=1:nCols %Plot Row Lines
XX=i*floor(width/nCols);
plot(ax,[XX XX],[1 height],'r','LineWidth',0.2)
end
hold(ax,"off");
end
I want to be able to toggle the whole grid on or off once its drawn. So I was wondering
1: How to group all the lines to one object?
2: If I pass that "object" as an output, how can I toggle on or off.
Thanks
Jason

Accepted Answer

Mathieu NOE
Mathieu NOE on 29 Sep 2025 at 9:50
hello
To group multiple lines into a single "object" in MATLAB, you can use a hggroup or hgtransform object.
here your code updated with hggroup
im = imread('your_image_here.jpg');
figure
imshow(im)
RowSize=40; % whatever number you want
ColSize=40; % whatever number you want
group = drawGrid(RowSize,ColSize,im,gca);
% Toggle visibility of the group
set(group, 'Visible', 'off'); % Hide all lines in the group
% and
set(group, 'Visible', 'on'); % Show all lines in the group
%%%%%%%%%%%%
function group = drawGrid(RowSize,ColSize,IM,ax)
% Rowsize=512
% Colsize=256
[height,width,p]=size(IM);
nRows=floor(height/RowSize);
nCols=floor(width/ColSize);
hold(ax,"on");
% Group the lines into a single object
group = hggroup; % create group
for i=1:nRows %plot Col Lines
prow{i} = plot(ax,[1 width],[i*RowSize i*RowSize],'r','LineWidth',0.2) ;
set(prow{i} , 'Parent', group);
end
for i=1:nCols %Plot Row Lines
XX=i*floor(width/nCols);
pcol{i} = plot(ax,[XX XX],[1 height],'r','LineWidth',0.2);
set(pcol{i} , 'Parent', group);
end
hold(ax,"off");
end
  8 Comments
Jason
Jason on 30 Sep 2025 at 11:48

Ok thsnks for your help and introducing me to hggrouo.

I think i have an easier way, but have run into another issue, so i will post a new question.

Sign in to comment.

More Answers (0)

Categories

Find more on Environment and Settings in Help Center and File Exchange

Tags

Products


Release

R2024b

Community Treasure Hunt

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

Start Hunting!