PHP7出来已经很久了,今天找资料的时候,发现PHP7版本增加了一个新扩展ui,能实现图形化的界面,大概尝试了一下,感觉类似java。官方链接见ui扩展,此扩展目前最高版本是2.0,支持php7.0和php7.1,tiandi试了在php7.2下安装,结果报错,估计要等下一个版本才能用在php7.2下了。
官方自带了3个DEMO,贪吃蛇,星空,和趋势图,都可以从上面的URL里介绍的git地址获取得到。看了贪吃蛇和星空的源码,简化了一下,tiandi制作了一个更简单的Demo,控制一个小方块在屏幕里上下左右移动。
代码如下,通过onKey事件来进行上下左右按键的行为。注意,这里需要判定当前方块的所在位置是否已出窗口边缘。
<?php
use UI\Window;
use UI\Point;
use UI\Size;
use UI\Area;
use UI\Key;
use UI\Controls\Box;
use UI\Draw\Pen;
use UI\Draw\Path;
use UI\Draw\Color;
use UI\Executor;
define('WINWIDTH',640); //窗口宽度
define('WINHEIGHT',480); //窗口高度
define('MYSIZE',20); //方块大小
$win = new class("可移动的方块DEMO", new Size(WINWIDTH, WINHEIGHT), false) extends Window {
public function addExecutor(Executor $executor) {
$this->executors[] = $executor;
}
protected function onClosing() {
foreach ($this->executors as $executor) {
$executor->kill();
}
$this->destroy();
UI\quit();
}
};
$box = new Box(Box::Vertical);
$win->add($box);
$stars = new class($box) extends Area {
protected function onKey(string $key, int $ext, int $flags) {
if ($flags & Area::Down) {
switch ($ext) {
case Key::Right:
if ($this->pos->x < WINWIDTH - MYSIZE) {
$this->pos->x += 10;
$this->redraw();
}
break;
case Key::Left:
if ($this->pos->x > 0) {
$this->pos->x -= 10;
$this->redraw();
}
break;
case Key::Down:
if ($this->pos->y < WINHEIGHT - MYSIZE) {
$this->pos->y += 10;
$this->redraw();
}
break;
case Key::Up:
if ($this->pos->y > 0) {
$this->pos->y -= 10;
$this->redraw();
}
break;
}
}
}
protected function onDraw(UI\Draw\Pen $pen, UI\Size $size, UI\Point $clip, UI\Size $clipSize) {
$hSize = $size / 2;
$path = new Path();
$path->addRectangle(Point::at(0), $size);
$path->end();
$pen->fill($path, 0x000000FF);
$path = new Path();
$pos = $this->pos;
$path->addRectangle($pos, new Size(MYSIZE, MYSIZE));
$path->end();
$color = new Color();
$color->r = 255;
$color->g = 0;
$color->b = 0;
$pen->fill($path, $color);
}
public function __construct($box) {
$this->box = $box;
$this->pos = $pos = new Point(0,0);
$this->box->append($this, true);
}
};
$animator = new class($stars) extends Executor {
protected function onExecute() {
$this->area->redraw();
}
public function __construct(Area $area) {
$this->area = $area;
parent::__construct();
}
};
$win->addExecutor($animator);
$win->show();
UI\run();
运行结果如下截图所示,可通过键盘的上下左右来控制红色方块的移动。

文章评分2次,平均分5.0:★★★★★

感谢楼主的分享,学习。
what! PHP 玩 UI 了?
用了还不成熟,感觉不行。
厉害了