Android游戏引擎libgdx使用教程:常用UI类与舞台(一)
像按钮、下拉框、列表、标签、图片、复选框、编辑框、分割面板、滑动面板、滑动条等都是比较常用的UI类,它们都属于Actor,可以很方便的纳入到舞台的管理中,而且都包含在com.badlogic.gdx.scenes.scene2d.ui包中,
其实仔细看看UI类的实现代码不难发现其实它们都是大部分继承自Widget或者Table,如果需要自定义UI可以继承以上两个类(它们继承自Actor),这里要说明一下libgdx的布局部分使用了TWL,有兴趣的朋友可以去看看。
在介绍每个控件之前我们先来看一下NinePatch,这是最近的一个比较重大的更新。
何为NinePatch?其实android原生即有NinePatch类,常在按钮中使用。
如图,将图片分成九份。中间部分可以根据需要扩大,使按钮的大小内容变动不受图片的限制。
而在libgdx的NinePatch其实就是九个TextureRegion对象。
常用的实例化方法有两个:
public NinePatch (Texture texture, int left, int right, int top, int bottom)
public NinePatch (TextureRegion region, int left, int right, int top, int bottom)
关于其中的四个int型参数如何取值我们可以参考一下源码:
public NinePatch (TextureRegion region, int left, int right, int top, int bottom) {
int middleWidth = region.getRegionWidth() - left - right;
int middleHeight = region.getRegionHeight() - top - bottom;
this.patches = new TextureRegion[] {new TextureRegion(region, 0, 0, left, top),
new TextureRegion(region, left, 0, middleWidth, top), new TextureRegion(region, left + middleWidth, 0, right, top),
new TextureRegion(region, 0, top, left, middleHeight), new TextureRegion(region, left, top, middleWidth, middleHeight),
new TextureRegion(region, left + middleWidth, top, right, middleHeight),
new TextureRegion(region, 0, top + middleHeight, left, bottom),
new TextureRegion(region, left, top + middleHeight, middleWidth, bottom),
new TextureRegion(region, left + middleWidth, top + middleHeight, right, bottom)};
}
先计算中间部分的宽度和高度。然后开始切图,首先取顶部的最左边的那个,即图中编号1的那块,然后去它右边的,然后再右边的。
取完最上边的那行,然后取中间的那行,然后取最后一行的。
由上自下,由左自右。
而在绘制时又是如何处理的呢?看源码:
-
android开发,青软培训