[英]Dragging an axes with a mouse within a figure: Matlab Gui Guide
該類的目的是允許用戶單擊圖像(即軸)並將其拖動到圖形上。 當檢測到鼠標單擊時,該函數將檢測鼠標位置位於哪些軸上,並啟動“ windowbuttonmotionfcn”,從而調用函數“ movit”。 “運動”功能的目的是在按下鼠標按鈕時拖動鼠標移動時選擇的軸。
function Mclicked(this, src, event)
% get location of mouse click on the gui
set(gca,'units','pix') ;
mousePositionData = get(gca, 'CurrentPoint')
this.x = mousePositionData(1,1);
this.y = mousePositionData(1,2);
%get origin position of all axes within the figure
set(gca,'units','pix') ;
AxesHandle=findobj(gcf,'Type','axes');
pt1 = get(AxesHandle,{'Position','tightinset'}); % [left bottom right top]
%get the axes that mouse as clicked on and it in Values as a mat
set(gcf,'windowbuttonmotionfcn',@( src, event) movit(this,src, event));
set(gcf,'windowbuttonupfcn',@( src, event) stopmovit(this, src, event));
end
end
我將鼠標第一次單擊時的原始位置存儲在變量x和y中。 下面的算法會在按下按鈕時獲取鼠標的新位置,並計算這兩次鼠標移動之間的差異/距離。 添加此差異以獲取軸的新位置。
function movit(this, src, event)
%get location of new mouse position on the gui
set(gca,'units','pix') ;
mousePositionData = get(gca, 'CurrentPoint')
this.x2 = mousePositionData(1,1);
this.y2 = mousePositionData(1,2);
this.distancex= this.x2-this.x;
this.distancey= this.y2-this.y;
%get the new location of the image.
this.x2=this.Values(1,1)+this.distancex;
this.y2=this.Values(1,2)+this.distancey;
set(gca,'Position',[this.x2 this.y2 this.h this.w]); %x y h w
drawnow;
end
我遇到的問題是軸不會在鼠標附近移動。 例如,當鼠標按鈕按下並且鼠標向下或什至向上移動時, 圖像/軸向下移動並消失 。 它不會與鼠標光標一起移動。
我做了一個測試,以驗證是否set(gca,'Position',[...]); %xyhw
set(gca,'Position',[...]); %xyhw
通過使用一個計數器在圖形上移動來正常工作,我將其加1並將其值添加到原始位置。 軸按預期移動並且對用戶可見。因此,請set(gca,'Position',[...]); %xyhw
set(gca,'Position',[...]); %xyhw
工作正常。 但是,我不確定是什么錯誤。 我假設它與我想調用的計算或一段代碼有關。
行mousePositionData = get(gca, 'CurrentPoint')
獲取軸內鼠標位置的坐標。 但是,我們需要獲取鼠標在圖形或gui中的位置。 因此,我將gca更改為gcf。
另外,我發現x和y坐標需要互換。 set(gca,'Position',[this.y2 this.x2 this.h this.w]); %xyhw
現在,圖像在鼠標光標旁邊移動。 仍然需要進行一些細微調整以完善它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.