2013-02-24 61 views
0

香港专业教育学院一直在努力改变特定rects的颜色rects数组当我触摸屏幕,但它似乎是工作,我的继承人代码:我如何更改Android中画布上的特定矩形颜色?

public Paint blue = new Paint(); 
RandomColorGen rc; 
ArrayList<Integer> colors = RandomColorGen.ColorList(5); 
Random rand = new Random(); 
int columns = 50; 
int rows = 50; 
Rect square[][] = new Rect[rows][columns]; 

public boolean isTouched; 
public Canvas canvas; 

    @Override 
protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
    this.canvas = canvas; 

    for (int x = 0; x < rows; x++) { 
     for (int y = 0; y < columns; y++) { 

      square[x][y] = new Rect(); 

      blue.setColor(colors.get(rand.nextInt(colors.size()))); 
      blue.setStyle(Paint.Style.FILL); 

      square[x][y].set(0, 0, (canvas.getWidth() - 10)/rows, 
        ((canvas.getHeight() - 100)/columns)); 
      square[x][y].offsetTo(x * ((canvas.getWidth() - 10)/rows), y 
        * ((canvas.getHeight() - 100)/columns)); 

      canvas.drawRect(square[x][y], blue); 


     } 
    } 
    if(isTouched){ 
     blue.setColor(colors.get(rand.nextInt(colors.size()))); 
     blue.setStyle(Paint.Style.FILL); 
     canvas.save(); 
     canvas.clipRect(square[1][1]); 
     canvas.drawRect(square[1][1], blue); 

     canvas.restore(); 

    } 

} 

@Override 
public boolean onTouchEvent(MotionEvent event) { 

    switch (event.getAction()) { 
    case MotionEvent.ACTION_DOWN: 
     isTouched = true; 


     break; 
    } 

    return true; 

} 

的colors.get()啄是颜色的arraylist。我采取了错误的方法?

回答

0

你将如何调用执行onTouch动作后的涂料功能...

OnTouch动作的第一个动作那么你如何调用paint()函数?

0

我只是测试你的代码,它的工作原理,但有几个值得一提的笔记:

  • 绘图期间分配的对象是一个非常不好的行为(特别是分配50 * 50时)!考虑将分配代码移到构造函数中,并在onDraw()方法中更改矩形的位置,如果要实现现在的相同行为。
  • 您的onTouchEvent()用法是不完整的,你需要有isTouched真实只要用户没有提出他的手,这是可以做到以下几点:

    @Override 
    public boolean onTouchEvent(MotionEvent event) { 
    
    switch (event.getAction()) { 
    case MotionEvent.ACTION_DOWN: 
        isTouched = true; 
    
    
        break; 
    case MotionEvent.ACTION_UP: 
    case MotionEvent.ACTION_CANCEL: 
        isTouched = false; 
        break; 
    
    } 
    invalidate(); 
    return true; 
    

    }

  • 每次还请布局您收到的TouchEvent使用invalidate()

+0

我想它移动到构造器和即时得到一个NullPointerException那里说平方[X] [Y] .SET(0,0,(canvas.getWidth() - 10)/行, \t \t \t \t \t \t((canvas.getHeight() - 100)/列)); – 2013-02-24 13:53:12

+0

也,我只想改变一个rects颜色,特别是方形[1] [1]。 – 2013-02-24 14:03:32