2016-12-19 45 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

相关问题