OpengGL ES2.0 Using NDK

时间:2024-08-29 10:33:20

使用C语言在Android Studio中编写OpenGL ES,首要的任务就是配置编程环境。

在最新的Android Studio中,可以直接编译C/C++源代码。本人的版本是Android Studio2.0。

1.程序结构图

OpengGL ES2.0 Using NDK

2.在local.properties中添加并确认ndk路径

ndk.dir=C\:\\Users\\Liroc\\AppData\\Local\\Android\\Sdk\\ndk-bundle
sdk.dir=C\:\\Users\\Liroc\\AppData\\Local\\Android\\Sdk

3.在gradle.properties中添加NDK支持

org.gradle.jvmargs=-Xmx4g -XX\:MaxPermSize\=512m
android.useDeprecatedNdk=true

4.在build.gradle(app)中添加ndk模块,同时需要增加子节点ldLibs,使程序在编译时,可以链接到libGLESv2.so

android {
compileSdkVersion 23
buildToolsVersion "24.0.1" defaultConfig {
applicationId "com.example.liroc.openglone"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0" ndk {
moduleName "game"
ldLibs "GLESv2"
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

5.添加native code

#include <GLES2/gl2.h>

void on_surface_created() {
glClearColor(1.0f, 1.0f, 0.0f, 0.0f);
} void on_surface_changed() { } void on_draw_frame() {
glClear(GL_COLOR_BUFFER_BIT);
}

6.添加相应的类来调用JNI代码

public class BasicNativeLib {
static {
System.loadLibrary("game");
} public static native void on_surface_created(); public static native void on_surface_changed(int width, int height); public static native void on_draw_frame();
}

7.相应的JNI函数

#include <jni.h>

JNIEXPORT void JNICALL Java_com_example_liroc_openglone_testone_BasicNativeLib_on_1surface_1created
(JNIEnv * env, jclass cls) {
on_surface_created();
} JNIEXPORT void JNICALL Java_com_example_liroc_openglone_testone_BasicNativeLib_on_1surface_1changed
(JNIEnv * env, jclass cls, jint width, jint height) {
on_surface_changed();
} JNIEXPORT void JNICALL Java_com_example_liroc_openglone_testone_BasicNativeLib_on_1draw_1frame
(JNIEnv * env, jclass cls) {
on_draw_frame();
}

8.最后,在我们的GLSurface.Renderer类中调用相应的方法即可

   private class SceneRenderer implements GLSurfaceView.Renderer {
BasicTriangle triangle; @Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
//glClearColor(0, 0, 0, 1.0f);
//triangle = new BasicTriangle(BasicGLSurfaceView.this);
BasicNativeLib.on_surface_created();
} @Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
//glViewport(0, 0, width, height);
BasicNativeLib.on_surface_changed(width, height);
} @Override
public void onDrawFrame(GL10 gl) {
//glClear(GL_COLOR_BUFFER_BIT);
//triangle.draw();
BasicNativeLib.on_draw_frame();
}
}

9.效果图

OpengGL ES2.0 Using NDK