How to get canvas pixel

牧云@^-^@ 提交于 2019-11-30 14:57:27

A canvas is nothing more than a container which holds drawing calls to manipulate a bitmap. So there is no concept of "taking colour from a canvas".

Instead, you should examine the pixels of the bitmap of the view, which you can get with getDrawingCache.

In your views' constructor:

this.setDrawingCacheEnabled(true);

When you want the colour of a pixel:

this.buildDrawingCache();
this.getDrawingCache(true).getPixel(x,y);

This is very inefficient if you are calling it many times in which case, you might want to add a bitmap field and use getDrawingCache() to set it in ondraw().

private Bitmap bitmap;

...

onDraw()

  ...

  bitmap = this.getDrawingCache(true);

Then use bitmap.getPixel(x,y);

Above answer returns me blank bitmap. This is my solution

@Override
protected void onDraw(Canvas canvas) {
    ...
    bitmapUpdated = true;
}

And then for getting bitmap

public Bitmap getBitmapImage() {
    if (bitmapUpdated) {
        this.buildDrawingCache();
        bitmapImage = Bitmap.createBitmap(this.getDrawingCache());
        this.destroyDrawingCache();
    }
    return bitmapImage;
}

This works fine for me, without excessive overhead.

Perhaps better solution would be to override invalidate() and onDraw() so it uses your canvas, that is linked with your bitmap

Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.draw(c);
return b;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!