【问题标题】:draw 2 pairs of resizable rectangles in matlab在matlab中绘制2对可调整大小的矩形
【发布时间】:2014-09-17 12:28:49
【问题描述】:

我有一个程序应该在 matlab 中绘制 2 个可调整大小的矩形。画两个可调整大小是可以的,但我想同时改变大小,我的意思是当我改变第一个的大小时,第二个的大小也会改变。但我不知道如何将它们连接在一起。有谁能够帮助我?! 谢谢。 这是我的代码:

figure,imshow('image.jpg');
h1 = imrect(gca, [10 10 300 500]);
h2 = imrect(gca, [200 200 400 300]);

【问题讨论】:

  • 请将您当前的代码与两个可单独调整大小的矩形一起放入您的问题中。可能答案只是对这段代码的微小修改。
  • 添加的代码,谢谢丹尼尔。
  • 鼠标点击并移动......你的意思是什么?
  • 没关系,我的错。

标签: matlab rectangles


【解决方案1】:

要解决这个问题,您必须使用addNewPositionCallback

编写您自己的函数来实现您需要的逻辑。此示例将所有矩形设置为相同大小:

function myPositionFunction(allRects,changed,position)
    %iterate over all rectangles
    for idx=1:numel(allRects)
        %skip the currently changed one
        if idx~=changed
            %get position, modify it and set it
            thisP=allRects(idx).getPosition();
            thisP(3:4)=position(3:4);
            allRects(idx).setPosition(thisP);
        end
    end
end

现在是棘手的部分,如何制作实际可用的回调:

figure
imshow('board.tif')
h1 = imrect(gca, [10 10 20 20]);
h2 = imrect(gca, [20 20 30 30]);
addNewPositionCallback(h1,@(p)myPositionFunction([h1,h2],1,p))
addNewPositionCallback(h2,@(p)myPositionFunction([h1,h2],2,p))

这样调用你的回调:

-first parameter a list of all rectangles (could be extended to more than two)
-second parameter the index of the changed rectangle
-third parameter the new boundaries of the changed rectangle

【讨论】:

  • 是否可以实时获取坐标?!通过 BluePos = 等待(h1);我有它们,鼠标双击后。但是如果我改变位置并再次调整矩形的大小,BluePos 不会改变:(
  • @Negar 在使用时总是调用 getPosition。然后它是最新的。
【解决方案2】:

我看到@Daniel 刚刚发布了一个答案,但这里还有一个使用 addNewPositionCallback 的替代解决方案。

1) 首先创建一个函数,在其中绘制第一个矩形,并添加回调:

function Draw2Rect(~)
global h1 

A = imread('peppers.png');

imshow(A);

h1 = imrect(gca,[20 20 200 150]);

addNewPositionCallback(h1,@UpdateRect)

2) 然后定义由回调调用的匿名函数,您首先在其中使用 findobj 来查找在当前轴上绘制的矩形。 imrect 对象的类型为“hggroup”。基本上你会寻找所有存在的矩形,当你移动第一个矩形时,以前的矩形被删除并绘制一个新的矩形。在这里,我使用了位置之间的虚拟关系,但你明白了。

function UpdateRect(~)

global h1 % Simpler to use global variables but there are more robust alternatives!

Rect1Pos = getPosition(h1); % Get the position of your rectangle of interest

hRect = findobj(gca,'Type','hggroup'); % Find all rectangle objects

if numel(hRect>1) Once you start changing the first rectangle position, delete others.
delete(hRect(1:end-1))
h2 = imrect(gca,round(Rect1Pos/2));
end

我不知道如何在答案中发布动画 gif,但这里有 2 个图像显示第一个矩形,然后是移动第一个矩形后的 2 个矩形:

1:

2:

希望对您有所帮助!如前所述,我使用 h1 作为全局变量来轻松地在函数之间传递数据,但您可以使用更强大的替代方案。

【讨论】:

  • 非常感谢Benoit,但丹尼尔的回答,这就是我想要的。
最近更新 更多