Tuesday 29 May 2012

Draw circle in Android RenderScript

Modify MyRSSurfaceView.java from last exercise "Perform transform of Translate and Rotate on RenderScript", to draw circle by combine a series of Triangle. Refer to the code, the larger the constant number_of_section, the more the shape close to circle.

circle in Android RenderScript


package com.exercise.AndroidRenderScript;

import android.content.Context;
import android.renderscript.Mesh;
import android.renderscript.RSSurfaceView;
import android.renderscript.RenderScriptGL;
import android.renderscript.RenderScriptGL.SurfaceConfig;

public class MyRSSurfaceView extends RSSurfaceView {

private RenderScriptGL renderScriptGL;
private ScriptC_RenderScript myScriptC;

public MyRSSurfaceView(Context context) {
super(context);
// TODO Auto-generated constructor stub
final RenderScriptGL.SurfaceConfig surfaceConfig
= new SurfaceConfig();
renderScriptGL = createRenderScriptGL(surfaceConfig);

myScriptC = new ScriptC_RenderScript(
renderScriptGL, getResources(), R.raw.renderscript);

myScriptC.set_my_rs_mesh(createMesh());

renderScriptGL.bindRootScript(myScriptC);
}

private Mesh createMesh(){

double radius = 100.0;
double angleInDegree, angleInRadian;

final int number_of_section = 18;
double ptX, ptY;

Mesh.TriangleMeshBuilder myMesh
= new Mesh.TriangleMeshBuilder(
renderScriptGL,
2,
Mesh.TriangleMeshBuilder.COLOR);

//index 0
myMesh.addVertex(0, 0);

//index 1
angleInDegree = 0;
angleInRadian = Math.toRadians(angleInDegree);
ptX = radius * Math.cos(angleInRadian);
ptY = radius * Math.sin(angleInRadian);
myMesh.addVertex((float)ptX, (float)ptY);

for(int i=0; i<number_of_section; i++){
angleInDegree += 360/number_of_section;
angleInRadian = Math.toRadians(angleInDegree);
ptX = radius * Math.cos(angleInRadian);
ptY = radius * Math.sin(angleInRadian);
myMesh.addVertex((float)ptX, (float)ptY);

myMesh.addTriangle(0, i+2, i+1);

}

return(myMesh.create(true));
};

}


Download the files.

No comments:

Post a Comment