taontech / githublog

一个基于github issues的博客系统,实时呈现,零依赖,零代码部署,不用打包不用上线。
4 stars 1 forks source link

OpenGLES 截图变暗的原因 #79

Open taontech opened 1 year ago

taontech commented 1 year ago

如果使用下面的方法截图,图片会变暗

    private fun createBitmapFromGLSurface(x: Int, y: Int, w: Int, h: Int, gl: GL10): Bitmap? {
        val bitmapBuffer = IntArray(w * h)
        val bitmapSource = IntArray(w * h)
        val intBuffer: IntBuffer = IntBuffer.wrap(bitmapBuffer)
        intBuffer.position(0)
        try {
            gl.glReadPixels(
                x, y, w, h, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE,
                intBuffer
            )
            var offset1: Int
            var offset2: Int
            for (i in 0 until h) {
                offset1 = i * w
                offset2 = (h - i - 1) * w
                for (j in 0 until w) {
                    val texturePixel = bitmapBuffer[offset1 + j]
                    val pixeln =
                        texturePixel and -0xff0100 or (texturePixel and 0x000000ff shl 16) or (texturePixel and 0x00ff0000 shr 16)
                    bitmapSource[offset2 + j] = pixeln
                }
            }
        } catch (e: GLException) {
            return null
        }
        return Bitmap.createBitmap(bitmapSource, w, h, Bitmap.Config.ARGB_8888)
    }

原因是保存的Bitmap的pixelformat 不对,需要把最后一行改成如下:

        return Bitmap.createBitmap(bitmapSource, w, h, Bitmap.Config.RGB_565)

就可以截到正常的图片。