我将屏幕划分为rects,但我正在使用for循环,因此我不会存储每次重新创建的rects。我如何将它们存储为数组?
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;}
}
}
答案 0 :(得分:2)
提前分配它们,这样您就不会在绘图操作期间实例化对象。因此,每当您确定需要的rects数量时(即如果它总是相同的,则在构造函数中初始化它们)。像这样:
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);
尽可能避免在绘图操作期间分配对象。
编辑:对于2D数组:
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);
答案 1 :(得分:1)
Rect rectArray[] = new Rect[5];
然后在循环内:
rectArray[i] = new Rect(srcX,srcY,srcX + width, srcY +height);
答案 2 :(得分: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