Dmytro Zarezenko
Dmytro Zarezenko

Reputation: 10686

Android, how get pixel color from Canvas?

I have a code like this:

// ...

public class MyImageView extends ImageView

    public MyImageView(Context context, String value /* some other params */) {
        super(context);

        // some predefines
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // some preparations
        try {
            // here I call third party lib like:
            someObj.draw(canvas);

            // HERE I WANT TO CHANGE COLOR OF SOME PIXELS ACCORDING TO THEIR CURRENT COLOR
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

In place of UPCASE letters comment I want to change color of some pixels on canvas according to their current color after third party lib drawing. I can use canvas.drawPoint(x, y, paint) method for set pixels color but how can I get color of some pixel by (x,y)?

Upvotes: 2

Views: 4061

Answers (1)

seesharper
seesharper

Reputation: 147

I might have something here (untested):

public static Bitmap getBitmap(Canvas canvas) {
    // mBitmap is a private value inside Canvas.
    // time for some dirty reflection:
    try {
        java.lang.reflect.Field field = Canvas.class.getDeclaredField("mBitmap");
        field.setAccessible(true);
        return (Bitmap)field.get(canvas);
    }
    catch (Throwable t) {
        return null;
    }
}

You can then access pixels by the following:

Bitmap map = getBitmap(canvas);
if (map != null) {
    int rgb = map.getPixel(100,100);
    int red = android.graphics.Color.red(rgb);
    ...
}

Upvotes: 1

Related Questions