如何更改android中画布上的特定rect颜色?

时间:2013-02-24 07:14:47

标签: java android colors grid android-canvas

当我触摸屏幕时,我一直试图改变一系列rects中特定rects的颜色,但它似乎不起作用,继承我的代码:

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()thingy是颜色的arraylist。我采取了错误的做法吗?

2 个答案:

答案 0 :(得分:0)

执行onTouch操作后如何调用paint函数...

OnTouch动作是第一个动作,所以你如何调用Paint()函数??

答案 1 :(得分:0)

我刚刚测试了你的代码,它有效,但有几个值得一提的说明:

  • 在绘图过程中分配对象是一种非常糟糕的行为(特别是在分配50 * 50时)!考虑将分配代码移动到构造函数,并在onDraw()方法中更改矩形的位置,如果您想实现与现在相同的行为。
  • 您对onTouchEvent()的使用尚未完成,只要用户没有举手,您就需要将isTouched设为true,这可以通过以下方式完成:

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

    }

  • 每次使用invalidate()

  • 收到 TouchEvent 时,也请求布局