2012-11-25 50 views
4

我有我画线画布:如何获得画布像素

//see code upd 

我需要吸管工具将颜色从我的画布。我该如何制作它?


代码UPD:

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

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

回答

11

画布不过是一个容器,其中包含绘制调用来操作位图。所以没有“从画布上取色”的概念。

相反,您应该检查视图的位图的像素,您可以使用getDrawingCache获得该位图的像素。

在你的观点的构造函数:

this.setDrawingCacheEnabled(true); 

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

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

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

private Bitmap bitmap; 

... 

onDraw() 

    ... 

    bitmap = this.getDrawingCache(true); 

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

+0

此代码工作正常仅供drawColor,但他并不认为它必须努力通过drawPath – Leo

+0

创建的颜色! getPixel就是这样做的。它直接从位图(即存储位图的字节数组)获取x,y处的像素,并且是您在屏幕上看到的。当drawPath方法渲染到位图时,它最终绘制像素,因此在此级别(getPixel),任何绘图调用之间没有区别。我怀疑x和y的数学可能是错误的。 – Simon