如何在安卓系统中获取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
}它总是返回一个黑色位图
发布于 2021-04-17 10:17:38
希望我能理解你的意思
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);https://stackoverflow.com/questions/67135823
复制相似问题