2016-06-12 144 views
2

我想創建幾何形狀的填充圖,可以通過按鈕或鍵盤擊中來上下移動。首先,不會同時出現,所以我不得不使用它們。按下後,他們確實向上移動,但他們以前的位置仍保持填充狀態,即它們被複制,雖然我已經轉過身.PS,我也想在被某個物體碰觸時摧毀一個物體。我們如何解決這個問題?MATLAB:通過按鈕同時繪製使用座標軸繪製的GUI對象

這裏是一段代碼:

global x 
global y 
global a 
global b 

a = [ 7 8 9 8 ]; 
b = [ 2 1 2 3 ]; 
x= [ 1 3 3 1]; 
y = [ 1 1 3 3]; 

fill(x,y,[0.3 0.7 0.2]); 

fill(a,b,[0.3 0.2 0.7]) 

axis([0,15,0,15]) 


% --- Executes on button press in up. 
function up_Callback(hObject, eventdata, handles) 

hold off 
global x 
global y 
global a 
global b 
y = y+2; 
b=b+2; 
hold on 
fill(x,y,[0.3 0.7 0.2]) 
fill(a,b,[0.3 0.2 0.7]) 
hold off 
axis([0,15,0,15]) 

回答

1

的技巧是使用的fill()的返回值來改變X/Y的數據。

function main 

    close all; 
    figure; 
    hold on; 

    objects(1) = struct('X',[ 7 8 9 8 ],'Y',[ 2 1 2 3 ],'fill_handle',[],'Color',[0.3 0.7 0.2]); 
    objects(2) = struct('X',[ 1 3 3 1],'Y',[ 1 1 3 3],'fill_handle',[],'Color',[0.3 0.2 0.7]); 
    objects(3) = struct('X',[ 1 5 3 1]+3,'Y',[ 1 2 3 3]+2,'fill_handle',[],'Color',[0.6 0.6 0.3]); 

    for i=1:length(objects) 
     objects(i).fill_handle = fill(objects(i).X,objects(i).Y,objects(i).Color); 
    end 

    axis([0,15,0,15]) 

    function keyPressCallback(~,eventdata) 
     disp(eventdata.Key); 
     dx = 0; 
     dy = 0; 
     if strcmp(eventdata.Key, 'rightarrow') 
      dx = 1; 
     elseif strcmp(eventdata.Key, 'leftarrow') 
      dx = -1; 
     elseif strcmp(eventdata.Key, 'uparrow') 
      dy = 1; 
     elseif strcmp(eventdata.Key, 'downarrow') 
      dy = -1; 
     elseif strcmp(eventdata.Key, 'delete') 
      i=1; 
      delete(objects(i).fill_handle); 
      objects(i) = []; 
     elseif strcmp(eventdata.Key, 'escape') 
      close all; 
      return; 
     end 

     for i=1:length(objects) 
      objects(i).X = objects(i).X + dx; 
      objects(i).Y = objects(i).Y + dy; 
      set(objects(i).fill_handle, 'XData', objects(i).X); 
      set(objects(i).fill_handle, 'YData', objects(i).Y); 
     end 

    end 
    set(gcf,'WindowKeyPressFcn',@keyPressCallback); 

end 
+0

Gracias!這樣可行! 任何提示如何執行摧毀部分? –

+0

當場。只有一件事不起作用,就是通過鍵盤移動。每當我按下時,它都不會做任何事情,或者讓我去控制顯示最後命令的控制檯。其次,是否填寫命令支持填寫屬性的編輯?像邊框顏色等。 –

+0

不知道爲什麼用箭頭鍵移動不起作用,在這裏很好(R2015a,win64)。您可以使用'set()'和'get()'編輯填充圖,請閱讀文檔以獲取詳細信息:http://mathworks.com/help/matlab/ref/patch-properties.html – janismac