Draw a rectangle on an image in gui with mouse hover

21 views (last 30 days)
Abdulllah on 11 Jan 2019
Commented: Abdulllah on 14 Jan 2019
This question has two parts.
First I want to draw a rectangle on an image in gui only when the mouse hovers on the image. Secondly, if the user clicks the image execute some statements. Right now, I can only draw the rectangle on the image in following manner,
rectangle('Position', [-2,-2,c+4,r+4],'EdgeColor','r');
Abdulllah on 11 Jan 2019
I am sorry, I forget to reply second question. These statemens drawing the rectangle on image ver well.
rectangle('Position', [-2,-2,c+4,r+4],'EdgeColor','r');
New Bitmap Image.bmp

Sign in to comment.

Accepted Answer

Kevin Phung
Kevin Phung on 11 Jan 2019
Edited: Kevin Phung on 11 Jan 2019
You can use the 'WindowButtonMotionFcn' property of your figure,
f = figure;
with the callback function retrieving the position of your cursor:
function cursorPos(my_fig,event)
pos = get(my_fig,'CurrentPoint');
You know the position of your image with:
image_pos = get(image_handle,'Position')
so you can add the logic where if the position is within the bounds of the image: draw a rectangle; else, delete existing rectangle.
If you call the handle of your figure and see all the properties, you can see the various types of callbacks your function can trigger, for example:
WindowButtonDownFcn: ''
WindowButtonMotionFcn: ''
WindowButtonUpFcn: ''
WindowKeyPressFcn: ''
WindowKeyReleaseFcn: ''
WindowScrollWheelFcn: ''
The 'WindowButtonDownFcn' should be used for:
Hope this helps!
  1 Comment
Abdulllah on 14 Jan 2019
Hello, Thank you for your reply. I can now WindowButtonMotionFcn and can draw the rectangle. but I am I unable to find the postions of the image. If I find position of the image using
I get values in points (). and if I use
image_pos = get(eventdata.figure1,'Position')
I get value in even -ve (1084.2 -55.8 2033.6 1115.2). I dont know why negative,
I am using this logic now to draw the rectangle under the WindowButtonMotionFcn.
pos1 = getpixelposition(eventdata.axes1,true)
image_pos = get(eventdata.figure1,'Position')
matlabImage = imread(strcat(num2str(randArr(3)),'.tif'));
if ((currentp(1)<x2&&currentp(1)>x1)&&currentp(2)>y2&&currentp(2)<y1)
% axes(hObject.figure1);
rectangle('Position', [-2,-2,c+4,r+4],'EdgeColor','r','LineWidth',3);
rectangle('Position', [-2,-2,c+4,r+4],'EdgeColor',[0,0,0]','LineWidth',3);
I need to determine the values of x1,y1,x2,y2.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!

Translated by