一 imshow函数
如果读入了一个图像,那么使用imshow函数即可以完成图像的显示。那么这里多介绍三个函数imread、imresize和imwrite,使用方式如下,
image_matrix = imread(‘test.jpg’,'jpg'); % 读入图像, 第一个参数为图像名,第二个参数为图像格式
% 返回值为图像矩阵,在MATLAB中图像读入后表示为矩阵
image_matrix_resized = imresize(image_matrix, [ x, y ]); % 修改图像尺寸, 第一个参数为图像矩阵,第二个参数为2维向量,为图像尺寸参数
% 返回值为修改后图像矩阵
imshow(image_matrix_resized); % 显示图像
imwrite(image_matrix_resized, 'pic.bmp', 'bmp'); % 写出图像,第一个参数为图像矩阵,第二个参数为图像名,第三个参数为图像存储格式
二 主辅缓存
可以使用一个图像矩阵作为主缓存,在显示过程中,用imshow完成显示。
而另外的辅缓存在更新过程中使用,将所有的图像更新数据存储在辅缓存中,更新完成后将辅缓存内的数据拷贝到主缓存中,再显示即可。
三 演示
这个演示很简单,就是一个矩形的移动和大小变换。(- -,旋转算法比较麻烦,就以简单的为主了)
function part5(in)
global h;
if nargin
eval(in);
else
if isempty(h)
initialize
else
closefcn;
end
end
function render
global h;
% 更新矩形位置和大小
h.square.pos = fix(...
[h.square.center(1) + 150 * cos(h.square.angle), ...
h.square.center(2) + 150 * sin(h.square.angle)]);
h.square.size = fix(70+40*cos(h.square.angle));
h.square.angle = mod(h.square.angle+0.05,2*pi);
% 刷新缓存
h.pool = NaN*ones(600,600,3);
h.pool(...
h.square.pos(1)-h.square.size:h.square.pos(1)+h.square.size, ...
h.square.pos(2)-h.square.size:h.square.pos(2)+h.square.size, 1) ...
= 1;
h.pool(...
h.square.pos(1)-h.square.size:h.square.pos(1)+h.square.size, ...
h.square.pos(2)-h.square.size:h.square.pos(2)+h.square.size, 2) ...
= 1;
h.pool(...
h.square.pos(1)-h.square.size:h.square.pos(1)+h.square.size, ...
h.square.pos(2)-h.square.size:h.square.pos(2)+h.square.size, 3) ...
= 1;
% 正常情况下上述操作在辅缓存上进行,然后拷贝到主缓存,进入下面的显示阶段
imshow(h.pool)
function initialize
global h;
% 创建矩形
h.square.size = 10;
h.square.pos = [0,0];
h.square.angle = 0;
h.square.center = [300,300];
% 创建图像窗口
h.figure = figure(... !!!创建图像界面
'numbertitle','off', ... 关闭数字标题
'name','第五部分 IMSHOW实例',... 窗口标题
'units','pixels',... 窗口位置等信息的单位,设置为像素
'position',[0,0,600,600],... 窗口位置,仅需要设置窗口大小,后面用MOVEGUI函数完成居中的移动
'resize','off',...
'menu','none', ...
'deletefcn','part5(''closefcn'')');
movegui(h.figure,'center')
% 创建坐标系
h.axes = axes(... !!!创建坐标轴,作为游戏显示空间
'units','normalized',... 单位设置为归一化
'position',[0,0,1,1],... 利用归一化设置坐标轴铺满整个窗口
'color',[0,0,0],... 坐标轴背景色
'tickdir','out'); % 坐标轴小刻度朝向为外,也可以通过将其长度设置为极小值解决他占用界面的问题
% 创建主缓存
h.pool = NaN*ones(600,600,3); % 这里的演示程序仅建立了一个计时器,而且没有交互,加之MATLAB效率限制,这里未定义辅缓存
% 创建计时器
h.timer = timer(...
'busymode','drop', ...
'ExecutionMode','fixedrate', ...
'period',0.06, ... 采用这种方式来实现,MATLAB似乎效率很低,只有将帧率降低到这里才能勉强显示
'timerfcn','part5(''render'')');
start(h.timer)
function closefcn
global h;
if isfield(h,'figure') && ishandle(h.figure)
delete(h.figure);
end
if isfield(h,'timer') && isvalid(h.timer)
stop(h.timer);
delete(h.timer);
end
h =[];
四 小结
到了这里,这一系列的内容就结束了。本节主要就是介绍一下采用缓存这种想法来实现前面的思路。当然在MATLAB中,这种做法非常不值得推荐,MATLAB完全跟不上趟,不过如果你使用其他工具和语言,那么结果就不一样了。
希望这个系列能够帮助想学习MATALB GUI的你,或者是想做游戏的你,让我们一起奋斗吧