如何避免在 onDraw 方法中创建对象
How to avoid object creation inside the onDraw method
我知道在 onDraw
方法中创建对象的成本非常高。我想绘制一个圆角矩形矩阵,坐标是动态的,我不能缓存所有的矩形,因为我使用滚动视图并且可能有很多矩形,drawRoundRect
没有其他重载方法,它有原始参数,我被迫在每次迭代中创建一个 Rectangle 对象。谁能提出有效的解决方案?
@Override
protected void onDraw(Canvas canvas) {
int h = getMeasuredHeight();
int tileSize = h / rows;
for(int i = 0; i < rows; ++i) {
for(int j = 0; j < columns; ++j) {
int x = j * tileSize;
int y = i * tileSize;
canvas.drawRoundRect(new RectF(x, y, x + tileSize, y + tileSize), 10, 10, tilePaint);
}
}
}
这只是一个例子,矩形可以有任意坐标。
RectF
有 set(left, top, right, bottom
) 方法。您可以在构造函数上分配它,并使用此方法更改 Rectf 的边界。
mRect.set(x, y, x + tileSize, y + tileSize);
mRect 是 RectF mRect = new RectF();
我知道在 onDraw
方法中创建对象的成本非常高。我想绘制一个圆角矩形矩阵,坐标是动态的,我不能缓存所有的矩形,因为我使用滚动视图并且可能有很多矩形,drawRoundRect
没有其他重载方法,它有原始参数,我被迫在每次迭代中创建一个 Rectangle 对象。谁能提出有效的解决方案?
@Override
protected void onDraw(Canvas canvas) {
int h = getMeasuredHeight();
int tileSize = h / rows;
for(int i = 0; i < rows; ++i) {
for(int j = 0; j < columns; ++j) {
int x = j * tileSize;
int y = i * tileSize;
canvas.drawRoundRect(new RectF(x, y, x + tileSize, y + tileSize), 10, 10, tilePaint);
}
}
}
这只是一个例子,矩形可以有任意坐标。
RectF
有 set(left, top, right, bottom
) 方法。您可以在构造函数上分配它,并使用此方法更改 Rectf 的边界。
mRect.set(x, y, x + tileSize, y + tileSize);
mRect 是 RectF mRect = new RectF();