필터 지우기
필터 지우기

How to draw rectangle on a figure, based on mouse location?

조회 수: 12 (최근 30일)
Mark Golberg
Mark Golberg 2016년 7월 19일
댓글: Mark Golberg 2016년 7월 19일
Hello, I'd like to "live-draw" a rectangle on my figure, based on mouse location.
I'm using the following:
set (gcf, 'WindowButtonMotionFcn', @mg_BPP_mouseMove);
function mg_BPP_mouseMove(object,eventdata)
windowSize = 64;
C = get (gca, 'CurrentPoint');
topLeftCornerX = round(C(1,1)) - windowSize/2;
topLeftCornerY = round(C(1,2)) - windowSize/2;
width = windowSize;
height = windowSize;
imrect(gca, [topLeftCornerX, topLeftCornerY, width, height]);
end
Two questions:
1. How can I make the windowSize be an input variable of mg_BPP_mouseMove? I don't want explicitly define it within the function itself.
2. At the moment it draws lots of rectangles (like a "snake") as my mouse moves across the figure. I'd like to display only the last one. I mean, I would like to have one rectangle that "flows" with my mouse cursor.

채택된 답변

Guillaume
Guillaume 2016년 7월 19일
For 1, create an anonymous function that binds the window size to BPP_mouseMove (with an added input argument).
For 2, keep track of the previously drawn rectangle and delete it.
windowsize = 40;
set(gcf, 'WindowButtonMotionFcn', @(source, eventarg) mg_BPP_mouseMove(source, eventarg, windowsize));
function mg_BPP_mouseMove(object, eventdata, windowSize)
persistent lastrect;
C = get (gca, 'CurrentPoint');
topLeftCornerX = round(C(1,1)) - windowSize/2;
topLeftCornerY = round(C(1,2)) - windowSize/2;
width = windowSize;
height = windowSize;
if ~isempty(lastrect) && lastrect.isvalid
delete(lastrect);
end
lastrect = imrect(gca, [topLeftCornerX, topLeftCornerY, width, height]);
end

추가 답변 (1개)

Walter Roberson
Walter Roberson 2016년 7월 19일
  댓글 수: 1
Mark Golberg
Mark Golberg 2016년 7월 19일
편집: Mark Golberg 2016년 7월 19일
Thank you Walter.
A) could you help me with my first question also please?
B) getrect is not my intention. Please note, I'm using WindowButtonMotionFcn in order for the rectangle to appear without me pressing the mouse.

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

Community Treasure Hunt

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

Start Hunting!

Translated by