我创建了一个自定义视图,在其中绘制了多个不同颜色的弧线。
在触摸时,我怎样才能获得触摸点的颜色?
在 Java 中:
final Bitmap bitmap = Bitmap.createBitmap(customView.getWidth(), customView.getHeight(), Bitmap.Config.ARGB_8888);
customView.draw(new Canvas(bitmap));
customView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int color = bitmap.getPixel((int) event.getX(), (int) event.getY());
return true;
}
});
在 Kotlin 中:
val bitmap = Bitmap.createBitmap(customView.getWidth(), customView.getHeight(), Bitmap.Config.ARGB_8888)
customView.draw(Canvas(bitmap))
customView.setOnTouchListener(View.OnTouchListener { _, event ->
val color = bitmap.getPixel(event.x.toInt(), event.y.toInt())
true
})
上面的解决方案有两个步骤
第 1 步:获取视图的位图作为canvas is nothing more than a container which holds drawing calls to manipulate a bitmap
。由于视图可以根据用户事件或其他情况进行自我更新,因此需要在 onDraw 调用时更新位图。
请参阅此处如何操作。
步骤2:一旦掌握了位图,就可以从视图事件中获取x和y位置并获得像素的特定颜色。
请参阅此处如何操作。
引用 :: 位图
getPixel(int x, int y)
Returns the Color at the specified location.
Ex
<!--Java-->
int color = bitmapObject.getPixel(10, 10);
<!--Kotlin-->
val color = bitmap.getPixel(10, 10)