简体   繁体   中英

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) ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM