[英]Get pixel of SurfaceView in Android from onTouchEvent function
How to get pixel of SurfaceView in Android如何在 Android 中获取 SurfaceView 的像素
I want to extend the custom class of SurfaceView and override onTouchEvent
我想扩展 SurfaceView 的自定义 class 并覆盖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
}
It always returns a black Bitmap它总是返回黑色 Bitmap
Hopefully I understood what you meant希望我明白你的意思
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)
}
}
EDIT编辑
This code will save the last rendered bitmap, therefore allowing you to use the getPixel
function.此代码将保存最后渲染的 bitmap,因此允许您使用getPixel
function。
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)
}
}
}
For the onDraw function to be called you need to add these line in your activity:要调用 onDraw function,您需要在活动中添加以下行:
CustomSurfaceView surfaceView = findViewById(R.id.custom_surface_view);
surfaceView.setWillNotDraw(true);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.