1

I have created a custom view inside which I have drawn multiple arcs of different colors.

On touching how can I get the color of the touched point?

Ankush Kapoor
  • 365
  • 3
  • 13

3 Answers3

2

In 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;
            }
        });

In 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
})
Birju Vachhani
  • 6,072
  • 4
  • 21
  • 43
  • Don't forget to mark it as correct if it answer your question correctly..Thanks :) – Birju Vachhani Jul 22 '19 at 05:05
  • java.lang.RuntimeException: Unable to start activity ComponentInfo{com.abc.practiceproject/com.abc.practiceproject.MainActivity}: java.lang.IllegalArgumentException: width and height must be > 0 Getting this exception – Ankush Kapoor Jul 22 '19 at 05:10
  • In this solution how is bitmap going to update when view re draw itself or updates something on view? – Anmol Jul 22 '19 at 05:10
  • @Anmol This is memory efficient way for static views like creating color picker. if you want dynamic color picking then we have to do some tread off, you need to recreate the bitmap whenever your view changes. – Birju Vachhani Jul 22 '19 at 05:15
  • What about scaling? The above x, y coordinates will be innacurate. – gdyrrahitis Aug 29 '20 at 12:46
0

Solution to above has two step's

Step 1: Getting the bitmap for your View as canvas is nothing more than a container which holds drawing calls to manipulate a bitmap.As view can update itself based on user event's or some other case then bitmap need's to be updated on onDraw call.

refer here how to do it.

Step 2: And once you get hold of bitmap get the x and y position from event of view and get specific color of pixel.

refer here how to do it.

Anmol
  • 8,110
  • 9
  • 38
  • 63
0

Ref :: Bitmap

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)
Joker
  • 153
  • 14