【问题标题】:Get pixel of SurfaceView in Android from onTouchEvent function从 onTouchEvent 函数获取 Android 中 SurfaceView 的像素
【发布时间】:2021-07-12 02:31:45
【问题描述】:

如何在Android中获取SurfaceView的像素

我想扩展SurfaceView的自定义类并覆盖onTouchEvent

private fun getBitmap(): Bitmap {
    /*mSurfaceView!!.isDrawingCacheEnabled = true
    mSurfaceView!!.buildDrawingCache(true)
    val bitmap: Bitmap = Bitmap.createBitmap(mSurfaceView!!.drawingCache)
    // mSurfaceView!!.isDrawingCacheEnabled = false
    // mSurfaceView!!.destroyDrawingCache()*/
    val bitmap =
        Bitmap.createBitmap(
            mSurfaceView!!.width,
            mSurfaceView!!.height,
            Bitmap.Config.ARGB_8888
        )
    val canvas = Canvas(bitmap)
    mSurfaceView!!.draw(canvas)
    return bitmap
}

它总是返回一个黑色位图

【问题讨论】:

    标签: android kotlin surfaceview touch-event android-camera2


    【解决方案1】:

    希望我明白你的意思

    class CustomSurfaceView(context: Context?, attrs: AttributeSet?) : SurfaceView(context, attrs) {
    
        override fun onTouchEvent(event: MotionEvent?): Boolean {
    
            var x = event?.getX();
            var y = event?.getY();
    
            Log.d("CustomSurfaceView", "Pixel($x, $y)");
    
            return super.onTouchEvent(event)
        }
    }
    

    编辑

    此代码将保存最后渲染的位图,因此允许您使用getPixel 函数。

    class CustomSurfaceView(context: Context?, attrs: AttributeSet?) : SurfaceView(context, attrs) {
    
        var bitmap: Bitmap? = null;
    
        override fun onTouchEvent(event: MotionEvent?): Boolean {
    
            if(event != null) {
    
                val x = event?.x;
                val y = event?.y;
    
                if (bitmap != null) {
                    val pixel = bitmap?.getPixel(x!!.toInt(), y!!.toInt());
                    if (pixel != null)
                        Log.d("CustomSurfaceView", "rgb(${Color.red(pixel)}, ${Color.green(pixel)}, ${Color.blue(pixel)})");
                }
                Log.d("CustomSurfaceView", "Pixel($x, $y)");
    
            }
            return super.onTouchEvent(event)
        }
    
        override fun draw(canvas: Canvas?) {
            if(canvas != null) {
                val width = canvas.width;
                val height = canvas.height;
                bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
                if(bitmap != null)
                    super.draw(Canvas(bitmap!!))
            }else {
                super.draw(canvas)
            }
        }
    }
    

    要调用 onDraw 函数,您需要在活动中添加以下行:

    CustomSurfaceView surfaceView = findViewById(R.id.custom_surface_view);
    
    surfaceView.setWillNotDraw(true);
    

    【讨论】:

    • 是的,我需要getPixel(x, y)
    • 它不适合我!位图始终为空
    • 对不起,忘了说。我将答案编辑为正确
    • 位图在onTouchEvent处为空
    • mSurfaceView!!.draw(canvas)怎么样
    猜你喜欢
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 2013-04-01
    相关资源
    最近更新 更多