如何用GlSurfaceView创建位图?

在Cocos2d里,我想用Glsurfaceview截取图像,但是返回的却是透明图像,代码如下:

GlsurfaceView glv=CCDirector.sharedDirector().getOpenGLView();
glv.setDrawingCacheEnabled(true);
Bitmap bitmap=glv.getDrawingCache();

原问题:[Cocos2d]How to Create bitmap from GlSurfaceView

阅读 5.2k
1 个回答

答案
Peter:解决方案如下。

if (MainImageProcessingActivity.capture) {
        int width = MainImageProcessingActivity.w;
        int height = MainImageProcessingActivity.h;
        int screenshotSize = width * height;
        ByteBuffer bb = ByteBuffer.allocateDirect(screenshotSize * 4);
        bb.order(ByteOrder.nativeOrder());
        gl.glReadPixels(0, 0, width, height, GL10.GL_RGBA,
                GL10.GL_UNSIGNED_BYTE, bb);
        int pixelsBuffer[] = new int[screenshotSize];
        bb.asIntBuffer().get(pixelsBuffer);
        bb = null;
        Bitmap bitmap = Bitmap.createBitmap(width, height,
                Bitmap.Config.RGB_565);
        bitmap.setPixels(pixelsBuffer, screenshotSize - width, -width, 0,
                0, width, height);
        pixelsBuffer = null;

        short sBuffer[] = new short[screenshotSize];
        ShortBuffer sb = ShortBuffer.wrap(sBuffer);
        bitmap.copyPixelsToBuffer(sb);

        // Making created bitmap (from OpenGL points) compatible with
        // Android bitmap
        for (int i = 0; i < screenshotSize; ++i) {
            short v = sBuffer[i];
            sBuffer[i] = (short) (((v & 0x1f) << 11) | (v & 0x7e0) | ((v & 0xf800) >> 11));
        }
        sb.rewind();
        bitmap.copyPixelsFromBuffer(sb);
        MainImageProcessingActivity.captureBmp = bitmap.copy(Bitmap.Config.ARGB_8888,false);
        MainImageProcessingActivity.capture=false;
    }

DroidBot(提问者):感谢Peter,我把这个代码用于我的渲染器和onDraw方法里,非常好用!

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题