下面来详细讲解一下drawtriangles函数的使用方法。并且使用drawtriangles函数实现下面这种处理效果
因为这个方法是从AS3移植而来,所以它的使用方法和AS3基本一致,这里是AS3的drawtriangles函数API,大家可以参照一下
上次也说明过,移植后的drawtriangles函数,第4个之后的参数的含义不同,在这里它第4个参数表示分割线的线粗,第5个参数则表示分割线的颜色,如果不设定,则不显示分割线
drawTriangles函数的定义
- drawTriangles(vertices, indices, uvtData,thickness,color)
- vertices:由数字构成的矢量,其中的每一对数字将被视为一个坐标位置(一个 x, y 对)。vertices 参数是必需的。
- indices:一个由整数或索引构成的矢量,其中每三个索引定义一个三角形。如果 indexes 参数为 null,则每三个顶点(vertices 矢量中的 6 对 x,y)定义一个三角形。否则,每个索引将引用一个顶点,即 vertices 矢量中的一对数字。例如,indexes[1] 引用 (vertices[2], vertices[3])。
- uvtData:由用于应用纹理映射的标准坐标构成的矢量。每个坐标引用用于填充的位图上的一个点。每个顶点必须具有一个 UV 或一个 UVT 坐标。对于 UV 坐标,(0,0) 是位图的左上角,(1,1) 是位图的右下角。
- thickness:分割三角形的边框的线粗
- color:分割三角形的边框的颜色
可以看到,上图中显示了三角形的边框。
好了,接下来说说其他三个参数的用法,
1,第一个参数vertices,其实就是定义每个顶点的坐标,这几个顶点的顺序依次为下图
vertices参数中储存的就是上面的9个顶点的坐标,代码如下
- vertices = new Array();
- vertices.push(0, 0);
- vertices.push(0, 120);
- vertices.push(0, 240);
- vertices.push(120, 0);
- vertices.push(120, 120);
- vertices.push(120, 240);
- vertices.push(240, 0);
- vertices.push(240, 120);
- vertices.push(240, 240);
对应图中的三角形,代码如下
- indices = new Array();
- indices.push(0, 3, 1);
- indices.push(3, 1, 4);
- indices.push(1, 4, 2);
- indices.push(4, 2, 5);
- indices.push(3, 6, 4);
- indices.push(6, 4, 7);
- indices.push(4, 7, 5);
- indices.push(7, 5, 8);
2,第三个参数uvtData是定义上面的每个顶点相对于整张图片的比例,比如上面的图中的9个顶点的坐标,他们相对于原图片中的位置分别为下图所示
换算成代码如下
- uvtData = new Array();
- uvtData.push(0, 0);
- uvtData.push(0, 0.5);
- uvtData.push(0, 1);
- uvtData.push(0.5, 0);
- uvtData.push(0.5, 0.5);
- uvtData.push(0.5, 1);
- uvtData.push(1, 0);
- uvtData.push(1, 0.5);
- uvtData.push(1, 1);
有了上面这些参数的定义,然后通过LSprite对象的graphics属性的beginBitmapFill和drawTriangles两个函数,就可以绘制多样化的图形了
beginBitmapFill是用位图图像填充绘图区,参数是LBitmapData对象
如果,在vertices参数中定义的坐标位置就是原图片中所对应的位置,那么图片是没有什么变化的,但是,如果改变这些坐标的位置,比如下面的代码
- vertices = new Array();
- vertices.push(0, 0);
- vertices.push(0-50, 120);//这里将原坐标的x坐标左移50
- vertices.push(0, 240);
- vertices.push(120, 0);
- vertices.push(120, 120);
- vertices.push(120, 240);
- vertices.push(240, 0);
- vertices.push(240+50, 120);//这里将原坐标的x坐标右移50
- vertices.push(240, 240);
- indices = new Array();
- indices.push(0, 3, 1);
- indices.push(3, 1, 4);
- indices.push(1, 4, 2);
- indices.push(4, 2, 5);
- indices.push(3, 6, 4);
- indices.push(6, 4, 7);
- indices.push(4, 7, 5);
- indices.push(7, 5, 8);
- uvtData = new Array();
- uvtData.push(0, 0);
- uvtData.push(0, 0.5);
- uvtData.push(0, 1);
- uvtData.push(0.5, 0);
- uvtData.push(0.5, 0.5);
- uvtData.push(0.5, 1);
- uvtData.push(1, 0);
- uvtData.push(1, 0.5);
- uvtData.push(1, 1);
- backLayer.graphics.beginBitmapFill(bitmapData);
- backLayer.graphics.drawTriangles(vertices, indices, uvtData);
效果如图
上面的变形是将图片分割成了8个三角形,要实现更多种变形,那只需要将图片分割成更多的小三角形就可以了
比如我利用这个函数,制作了一个简陋的图片修饰工具,效果如下