0

I have a custom view and I want to get pixel by a given position on ACTION_UP event.

public class MyView extends View
{
    private Bitmap mBitmap;
    private Canvas mCanvas;
    private Paint mPaint;

    public MyView(Context context)
    {
        super(context);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);

        setDrawingCacheEnabled(true);

        mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);

        mPaint = new Paint();
        mPaint.setColor(Color.RED);
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setStrokeWidth(20f);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        canvas.drawBitmap(mBitmap, 0, 0, mPaint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        switch (event.getAction())
        {
            case MotionEvent.ACTION_UP:
            {
                float x = event.getX();
                float y = event.getY();

                int pixel = mBitmap.getPixel((int) x, (int) y);

                Log.i("APP", "Pixel is: " + pixel);

                return true;
            }
        }

        return super.onTouchEvent(event);
    }
}

I'm getting only 0 when I'm calling mBitmap.getPixel(x, y);

enter image description here

  • I've marked the ontouch events on the image with black circle
Zbarcea Christian
  • 9,367
  • 22
  • 84
  • 137

1 Answers1

0

You create a bitmap, and a canvas for that bitmap. But you never draw to it. Since you never draw to it, it will be whatever the default value of a new bitmap is, which is most likely to be either random or 0.

Unless you didn't post the drawing code, in which case we'll need that too.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127