Creating a bitmap of a drawn square in android ope

2019-04-17 21:48发布

问题:

I have drawn a square using opengl es 2.0 and now i want to create a bitmap of that drawn square. Can anyone please guide me on how to do that? Please let me know if my question is not clear. Thanks

回答1:

It is done using glReadPixels(). This is slow, but is the only method available with OpenGL ES 2.0 on Android. In Java:

Bitmap buttonBitmap = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
ByteBuffer byteBuffer = ByteBuffer.allocateDirect(mWidth * mHeight * 4);
GLES20.glReadPixels(0, 0, mWidth, mHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, byteBuffer);
buttonBitmap.copyPixelsFromBuffer(byteBuffer);

However, it is considerably faster if implemented in native code:

JNIEXPORT jboolean JNICALL Java_com_CopyToBitmap(JNIEnv * env, jclass clazz, jobject bitmap)
{
AndroidBitmapInfo   BitmapInfo;
void *              pPixels;
int                 ret;

if ((ret = AndroidBitmap_getInfo(env, bitmap, &BitmapInfo)) < 0)
{
    LOGE("Error - AndroidBitmap_getInfo() Failed! error: %d", ret);
    return JNI_FALSE;
}

if (BitmapInfo.format != ANDROID_BITMAP_FORMAT_RGBA_8888)
{
    LOGE("Error - Bitmap format is not RGBA_8888!");
    return JNI_FALSE;
}

if ((ret = AndroidBitmap_lockPixels(env, bitmap, &pPixels)) < 0)
{
    LOGE("Error - AndroidBitmap_lockPixels() Failed! error: %d", ret);
    return JNI_FALSE;
}

glReadPixels(0, 0, BitmapInfo.width, BitmapInfo.height, GL_RGBA, GL_UNSIGNED_BYTE, pPixels);

AndroidBitmap_unlockPixels(env, bitmap);
return JNI_TRUE;
}