如何获得画布像素

Leo*_*Leo 5 android colors android-canvas

我画了一条画线:

//see code upd
Run Code Online (Sandbox Code Playgroud)

我需要制作移液器工具,它将从我的画布中获取颜色.我该怎么做?


代码更新:

private static class DrawView extends View 
{
        ...
        public DrawView(Context context) {
            super(context);
            setFocusable(true);

            mBitmap = Bitmap.createBitmap(640, 860, Bitmap.Config.ARGB_8888);
            mCanvas = new Canvas(mBitmap);
            mPath = new Path();
            mBitmapPaint = new Paint(Paint.DITHER_FLAG);

            this.setDrawingCacheEnabled(true);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            canvas.drawColor(0xFFAAAAAA);
            canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
            canvas.drawPath(mPath, mPaint);
        }
        private void touch_up()
        {
            if(!drBool) //is true when I click pipette button
            {
                ...
                mCanvas.drawPath(mPath, mPaint); // lines draw
                mPath.reset();
            }else{
                this.buildDrawingCache();
                cBitmap = this.getDrawingCache(true);
                if(cBitmap != null)
                {
                    int clr = cBitmap.getPixel((int)x, (int)y);
                    Log.v("pixel", Integer.toHexString(clr));
                    mPaint.setColor(clr);
                }else{
                    Log.v("pixel", "null");
                }
            }
            drBool = false;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我只看到"像素" - "ffaaaaaa",或者如果我使用mCanvas.drawColor(Color.GRAY)"pixel" - "ff888888"

Sim*_*mon 13

画布只不过是一个容纳绘图调用来操作位图的容器.所以没有"从画布上取色"的概念.

相反,您应该检查视图位图的像素,您可以使用它getDrawingCache.

在视图的构造函数中:

this.setDrawingCacheEnabled(true);
Run Code Online (Sandbox Code Playgroud)

当你想要一个像素的颜色:

this.buildDrawingCache();
this.getDrawingCache(true).getPixel(x,y);
Run Code Online (Sandbox Code Playgroud)

如果你多次调用它,这是非常低效的,在这种情况下,你可能想要添加一个位图字段并使用getDrawingCache()在ondraw()中设置它.

private Bitmap bitmap;

...

onDraw()

  ...

  bitmap = this.getDrawingCache(true);
Run Code Online (Sandbox Code Playgroud)

然后用 bitmap.getPixel(x,y);