原理是用多个多边形组成类圆形的Mesh,再用一个圆形黑色半透明的图片生成Texture,调用bind()方法,最后渲染mesh。
texture.bind();
mesh.render(GL10.GL_TRIANGLE_FAN);
看代码:
public class ProgressTimer {
public static final int DIRECTION_CLOCKWISE = -1;
public static final int DIRECTION_COUNTERCLOCKWISE = 1;
private int MAX_VERTICE;
private int MIN_VERTICE;
private Texture texture;
private Mesh mesh;
private int iVertice;
private float r;
private float fCenterX;
private float fCenterY;
private int iDirection;
public ProgressTimer(AssetManager manager, float centerX, float centerY, float r, int maxVertice, int minVertice, String textureName, int direction) {
fCenterX = centerX;
fCenterY = centerY;
this.r = r;
MAX_VERTICE = maxVertice – minVertice;
MIN_VERTICE = minVertice;
texture = manager.get(textureName, Texture.class);
iDirection = direction;
}
public void draw(float progress) {
createMesh(progress);
texture.bind();
mesh.render(GL10.GL_TRIANGLE_FAN);
}
private void createMesh(float progress) {
iVertice = (int) (MAX_VERTICE * progress) + MIN_VERTICE;
double fTotalAngle = progress * 2 * Math.PI;
double fPerAngle = fTotalAngle / (iVertice – 2);
if(mesh != null)
mesh.dispose();
mesh = new Mesh(true, iVertice * 3, iVertice,
new VertexAttribute(Usage.Position, 3, “point”),
new VertexAttribute(Usage.TextureCoordinates, 2, “texCoords”));
float[] vertices = new float[iVertice * 5];
short[] indexs = new short[iVertice];
vertices[0] = fCenterX;
vertices[1] = fCenterY;
vertices[2] = 0;
vertices[3] = 0.5f;
vertices[4] = 0.5f;
indexs[0] = 0;
for(int i = 1; i < iVertice; i ++){
float fAngle = (float) (iDirection * fPerAngle * (i – 1));
indexs[i] = (short) i;
for(int j = 0; j < 5; j ++){
int iIndex = i * 5 + j;
switch(j)
{
case 0:
vertices[iIndex] = (float) (fCenterX + r * Math.cos(fAngle));
break;
case 1:
vertices[iIndex] = (float) (fCenterY + r * Math.sin(fAngle));
break;
case 2:
vertices[iIndex] = 0;
break;
case 3:
vertices[iIndex] = (float) ( (Math.cos(fAngle) + 1) / 2);
break;
case 4:
vertices[iIndex] = (float) ( ((- Math.sin(fAngle)) + 1) / 2);
break;
}
}
}
mesh.setVertices(vertices);
mesh.setIndices(indexs);
}
}
使用方法
ProgressTimer progress = new ProgressTimer(manager, centerX, centerY, r, 16, 3, textureName, ProgressTimer.DIRECTION_COUNTERCLOCKWISE);
progress.draw(fCurTime / iCD);