2016-12-19 46 views
0

我有兩個類:CustomView擴展視圖和MainActivity擴展活動。在CustomView中,我使用循環繪製了一系列圓角正方形(canvas.drawRoundRect)。我知道如何檢測任何特定廣場上的點擊,但我不知道如何更改廣場的顏色。我如何從MainActivity調用onDraw方法?或者如果有一個更新方法可以用來從MainActivity類中取消invalidate()。底線是我想知道如何改變我的形狀的顏色,每當我點擊它。謝謝。Android:我繪製了很多形狀。我需要改變一個形狀的顏色,每當我點擊它

+1

有)一個無效()方法的意見,這將調用的onDraw方法https://developer.android.com/reference/android/view/View.html#invalidate( –

回答

0

使用以下命令:一旦你在Java代碼命名,並宣佈他們的形式,你可以按照如下它的名字叫對象,並將以下更改:

"Name of the object" .setbackgroundColor ("Name of the object" .getContext().GetResources(). GetColor (R.color. "Desired color") 
0

在你的onDraw()方法通過在varible

@Override 
protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
    firstPaint.setColor(firstRectColor); 
    canvas.drawRoundRect(//..,firstPaint); 
    //.. 
    setOnTouchListener(new View.OnTouchListener() { 
     @Override 
     public boolean onTouch(View view, MotionEvent motionEvent) { 
      if(motionEvent.getAction()==MotionEvent.ACTION_DOWN){ 
       if(((motionEvent.getX()>=firstRectX) && (motionEvent.getX()<=firstRectX+firstRectWidth))&&((motionEvent.getY()>=firstRectY) && (motionEvent.getY()<=firstRectY+firstRectHeight))){ 
       //touch point is inside first rectangle 
       //assign the color to firstRectColor variable and call invalidate to redraw 
       firstRectColor=getColorToChange(); 
       invalidate(); 
       }//..else if(){} 
      } 
      return true; 
     } 
    }); 
} 
+0

謝謝它完美的作品! – Sandman

+0

如果工作正常,請標記爲正確答案 –

0

對於這一點,你需要得到被點擊的像素的顏色,然後用下面的洪水填充算法,並通過您的位圖,點設置油漆顏色繪製您的矩形,你點擊了位圖,目標和替換顏色代碼。

private void FloodFill(Bitmap bmp, Point pt, int targetColor, int replacementColor) 
    { 
     Queue<Point> q = new LinkedList<Point>(); 
     q.add(pt); 
     while (q.size() > 0) { 
      Point n = q.poll(); 
      if (bmp.getPixel(n.x, n.y) != targetColor) 
       continue; 

      Point w = n, e = new Point(n.x + 1, n.y); 
      while ((w.x > 0) && (bmp.getPixel(w.x, w.y) == targetColor)) { 
       bmp.setPixel(w.x, w.y, replacementColor); 
       if ((w.y > 0) && (bmp.getPixel(w.x, w.y - 1) == targetColor)) 
        q.add(new Point(w.x, w.y - 1)); 
       if ((w.y < bmp.getHeight() - 1) 
         && (bmp.getPixel(w.x, w.y + 1) == targetColor)) 
        q.add(new Point(w.x, w.y + 1)); 
       w.x--; 
      } 
      while ((e.x < bmp.getWidth() - 1) 
        && (bmp.getPixel(e.x, e.y) == targetColor)) { 
       bmp.setPixel(e.x, e.y, replacementColor); 

       if ((e.y > 0) && (bmp.getPixel(e.x, e.y - 1) == targetColor)) 
        q.add(new Point(e.x, e.y - 1)); 
       if ((e.y < bmp.getHeight() - 1) 
         && (bmp.getPixel(e.x, e.y + 1) == targetColor)) 
        q.add(new Point(e.x, e.y + 1)); 
       e.x++; 
      } 
     } 
    } 

您可以搜索更多關於填充算法的麪糊理解。

https://github.com/latemic/ColorBooth/blob/master/src/com/colorbooth/FloodFill.java

相關問題