首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从SurfaceView函数获取安卓系统中的onTouchEvent像素

从SurfaceView函数获取安卓系统中的onTouchEvent像素
EN

Stack Overflow用户
提问于 2021-04-17 07:36:43
回答 1查看 237关注 0票数 0

如何在安卓系统中获取SurfaceView像素

我想扩展SurfaceView的自定义类并重写onTouchEvent

代码语言:javascript
复制
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
}

它总是返回一个黑色位图

EN

回答 1

Stack Overflow用户

发布于 2021-04-17 10:17:38

希望我能理解你的意思

代码语言:javascript
复制
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函数。

代码语言:javascript
复制
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函数,需要在活动中添加以下行:

代码语言:javascript
复制
CustomSurfaceView surfaceView = findViewById(R.id.custom_surface_view);

surfaceView.setWillNotDraw(true);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67135823

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档