我正在尝试制作http://arapaho.nsuok.edu/~deckar01/Zvis.html的原生 Android 版本
所以,我制作了一个自定义视图来绘制所有需要的正方形。当然,一旦数字变得足够大以使 Canvas 开始绘制数千个正方形,此绘图最终将花费 10 秒。
有一个更好的方法吗?似乎有一些明显的事情我不想做/使用。
视图的 onDraw 方法如下,以防万一。有任何想法吗?
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
final int number = mNumber;
final float tileWidth, tileHeight;
/*mTileWidth = mWW / (number - 1);
mTileHeight = mHH / (number - 1);*/
// make them squares
if (mWW <= mHH) {
tileWidth = tileHeight = mWW / (number - 1);
} else {
tileWidth = tileHeight = mHH / (number - 1);
}
mWhiteTextPaint.setTextSize(48f / 72 * tileWidth);
mBlackTextPaint.setTextSize(48f / 72 * tileWidth);
float currX = getPaddingLeft();
float currY = getPaddingTop();
for (int i = 1; i <= number - 1; i++) {
mBackgroundPaint.setColor(getBackgroundColor(i, number));
canvas.drawRect(currX, currY, currX + tileWidth,
currY + tileHeight,
mBackgroundPaint);
final String text = String.valueOf(i);
canvas.drawText(text,
currX + tileWidth / 2 - mWhiteTextPaint.measureText(text) / 2,
currY + tileHeight * 0.9f, mWhiteTextPaint);
currX += tileWidth;
}
currX = getPaddingLeft();
currY += tileHeight;
for (int i = 2; i <= number - 1; i++) {
for (int j = 1; j <= number - 1; j++) {
final int num = (j == 1) ? i : (i * j) % number;
mBackgroundPaint.setColor(getBackgroundColor(num, number));
canvas.drawRect(currX, currY, currX + tileWidth,
currY + tileHeight,
mBackgroundPaint);
final String text = String.valueOf(num);
if (num == 0) {
canvas.drawText(text,
currX + tileWidth / 2 - mBlackTextPaint.measureText(text) / 2,
currY + tileHeight * 0.9f, mBlackTextPaint);
} else {
canvas.drawText(text,
currX + tileWidth / 2 - mWhiteTextPaint.measureText(text) / 2,
currY + tileHeight * 0.9f, mWhiteTextPaint);
}
currX += tileWidth;
}
currX = getPaddingLeft();
currY += tileHeight;
}
if (mOnDrawFinishedListener != null) {
mOnDrawFinishedListener.onDrawFinished(number);
}
}