在matlab创建写字板并能保存用鼠标所画的图片
时间: 2024-05-08 22:15:53 浏览: 8
以下是一个基本的Matlab写字板程序,可以创建一个GUI界面,允许用户在画板上绘制,使用鼠标保存所画的图片。
```
function myPaint
% Create a GUI with drawing canvas and save button
% Create a new figure window
hFig = figure('Toolbar','none',...
'Menubar', 'none',...
'NumberTitle','off',...
'Name','Paint',...
'Units','normalized',...
'Position',[0.2 0.2 0.6 0.6]);
% Create a new drawing canvas
hAx = axes('Parent',hFig,...
'Units','normalized',...
'Position',[0.05 0.05 0.9 0.85],...
'XLim',[0 1],'YLim',[0 1],...
'XTick',[],'YTick',[],...
'Color',[1 1 1]);
% Create a save button
hButton = uicontrol('Parent',hFig,...
'Style','pushbutton',...
'String','Save',...
'Units','normalized',...
'Position',[0.4 0.92 0.2 0.05],...
'Callback',@saveButton_Callback);
% Initialize the drawing state
drawing = false;
lastPoint = [];
% Define the callback function for mouse button down
set(hAx,'ButtonDownFcn',@startDrawing);
% Define the callback function for mouse movement
set(hFig,'WindowButtonMotionFcn',@drawLine);
% Define the callback function for mouse button up
set(hFig,'WindowButtonUpFcn',@stopDrawing);
% Callback function for mouse button down
function startDrawing(hObject, eventdata)
drawing = true;
lastPoint = get(hAx,'CurrentPoint');
lastPoint = lastPoint(1,1:2);
end
% Callback function for mouse movement
function drawLine(hObject, eventdata)
if drawing
currentPoint = get(hAx,'CurrentPoint');
currentPoint = currentPoint(1,1:2);
line([lastPoint(1) currentPoint(1)], [lastPoint(2) currentPoint(2)],...
'Color','k','LineWidth',2);
lastPoint = currentPoint;
end
end
% Callback function for mouse button up
function stopDrawing(hObject, eventdata)
drawing = false;
end
% Callback function for save button
function saveButton_Callback(hObject, eventdata)
[filename, pathname] = uiputfile({'*.png';'*.jpg';'*.bmp';'*.tif'},'Save As');
if isequal(filename,0) || isequal(pathname,0)
return;
end
print(hFig, fullfile(pathname, filename), '-dpng', '-r300');
end
end
```
运行此程序后,您可以使用鼠标在画板上绘制任何图形。点击保存按钮将弹出文件对话框,允许您选择要保存的文件类型和位置。程序将绘图保存为PNG,JPG,BMP或TIF格式中的一个。