0

我已将屏幕分成矩形,但我使用的是 aa for 循环,因此我不会将矩形存储在那里每次都重新制作。我将如何将它们存储在数组中?

     public void drawGrid() {
    //android.os.Debug.waitForDebugger();
    int height,width;
    int column,row;
    int maxColumn,maxRow;
    maxColumn = 4;
    maxRow = 4;
    column = 0;
    row = 0;
    height = c.getHeight()/maxRow;
    width = c.getWidth()/maxColumn;
    Paint pg = new Paint();
    Rect[] test[];


    for(int i = 0;i < 5; i++) {
        int srcX = column * width;
        int srcY = row * height;
        Rect src =new Rect(srcX,srcY,srcX + width, srcY +height);
        pg.setColor(Color.WHITE);
        pg.setStyle(Paint.Style.STROKE);
        pg.setStrokeWidth(5);
        c.drawRect(src, pg);
        if (column == maxColumn && row == maxRow){
            i = 5;
        } else {i=0;}
        if (column == maxColumn){
            row = row + 1;
            column = 0;
        } else {column = column + 1;}

    }



}
4

3 回答 3

2

提前分配它们,这样您就不会在绘图操作期间实例化对象。因此,每当您确定所需的矩形数量时(即,如果它始终相同,请在构造函数中初始化它们)。像这样的东西:

Rect[] rects = new Rect[rectCount];
for(int i = 0; i < rectCount; i++) rects[i] = new Rect();

然后,在您的绘图循环中,使用:

rects[i].set(srcX, srcY, srcX + width, srcY + height);

您应该尽可能避免在绘制操作期间分配对象。

编辑:对于二维数组:

Rect[][] rects = new Rect[rowCount][colCount];
for(int i = 0; i < rowCount; i++) {
    for(int j = 0; j < colCount; j++) {
        rects[i][j] = new Rect();
    }
}

然后在循环中,它是同样的事情:

rects[row][col].set(srcX, srcY, srcX + width, srcY + height);
于 2013-03-05T21:16:32.940 回答
1
Rect rectArray[] = new Rect[5];

然后在循环内:

rectArray[i] = new Rect(srcX,srcY,srcX + width, srcY +height);
于 2013-03-05T21:14:35.353 回答
1

你总是会有固定数量的矩形吗?您可能想考虑一个数组列表?

ArrayList<Rect> rects = new ArrayList<Rect>();
rects.add(new Rect(srcX,srcY,srcX + width, srcY +height));

你可以用这些东西轻松地做很多有用的东西,这里有一些例子:http: //javarevisited.blogspot.com.es/2011/05/example-of-arraylist-in-java-tutorial.html

于 2013-03-05T21:22:21.737 回答