从onTouchEvent函数获取Android中SurfaceView的像素
如何在Android中获取SurfaceView的像素 我想扩展SurfaceView和override的自定义类从onTouchEvent函数获取Android中SurfaceView的像素,android,kotlin,surfaceview,touch-event,android-camera2,Android,Kotlin,Surfaceview,Touch Event,Android Camera2,如何在Android中获取SurfaceView的像素 我想扩展SurfaceView和override的自定义类onTouchEvent private fun getBitmap(): Bitmap { /*mSurfaceView!!.isDrawingCacheEnabled = true mSurfaceView!!.buildDrawingCache(true) val bitmap: Bitmap = Bitmap.createBitmap(mSurface
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
}
它总是返回一个黑色位图,希望我能理解你的意思
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中为空!!。绘制(画布)