2012-11-25 51 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