how can I add label to rectangle object ?

My code : rect=rectangle('Position',pos);
draggable(rect); set(rect,'FaceColor','none','EdgeColor','g','LineWidth',6);
And now I want to add a label to the rectangle

Answers (1)

I am not familiar with the 'draggable' function, but this should give you a text box in the middle of the square.
text(pos(1)+pos(3)/2,pos(2)+pos(4)/2,'Title','HorizontalAlignment','center')

4 Comments

Thanks for your answer but the title is not draggable like the square
I did not go through the 'draggable' function, but I assume it allows you to interactively drag the square. I believe the following code should do the same:
pos = [1 2 5 6];
rect = rectangle('Position',pos);
set(rect,'FaceColor','none','EdgeColor','g','LineWidth',6);
axis([0 10 0 10])
rect_title(rect,'title')
Just define the following function first:
function rect_title(rect,str)
global updateflag
updateflag = false;
% Add initial title to UserData
rect.UserData.str = str;
rect.UserData.t = text(rect.Position(1)+rect.Position(3)/2,rect.Position(2)+rect.Position(4)/2,rect.UserData.str,'HorizontalAlignment','center');
% Add Callbacks
ax = rect.Parent;
f = ax.Parent;
f.WindowButtonUpFcn = @draw_rectangle;
rect.ButtonDownFcn = @draw_rectangle;
end
function draw_rectangle(src,evt)
global updateflag
if ishandle(src) && strcmp(get(src,'type'),'figure') && updateflag
% Assign temporary data to rect
RectData = src.UserData.RectData;
% Move Rectangle
Pold = RectData.rect.Position;
P1 = RectData.Pdown.IntersectionPoint;
P2 = evt.IntersectionPoint;
dx = P2(1) - P1(1);
dy = P2(2) - P1(2);
RectData.rect.Position = Pold + [dx dy 0 0];
% Update title
delete(RectData.t)
RectData.rect.UserData.t = text(RectData.rect.Position(1)+RectData.rect.Position(3)/2,RectData.rect.Position(2)+RectData.rect.Position(4)/2,RectData.rect.UserData.str,'HorizontalAlignment','center');
updateflag = false;
elseif ishandle(src) && strcmp(get(src,'type'),'rectangle')
updateflag = true;
ax = src.Parent;
f = ax.Parent;
f.UserData.RectData.t = src.UserData.t;
f.UserData.RectData.rect = src;
f.UserData.RectData.Pdown = evt;
end
end
thanks a lot
You are welcome. I hope it solved your problem.

Sign in to comment.

Tags

Asked:

on 3 Aug 2018

Commented:

on 6 Aug 2018

Community Treasure Hunt

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

Start Hunting!