画布上的动态绘图耗时太长

时间:2016-07-14 21:49:55

标签: java android performance android-canvas

我想绘制一个带有动画颜色属性的四边形网格,但结果是代码太慢而不仅仅是为了创建图像的基本结构,更不用说动画了它。此外,图像正在绘制,而不是完成计算,而是在部分过程中。我该如何解决?这是 onDraw(Canvas canvas) 方法:

protected void onDraw(Canvas canvas) {
    canvas.drawColor(Color.BLACK);

    final int height = canvas.getHeight();
    final int width = canvas.getWidth();

    Bitmap.Config conf = Bitmap.Config.RGB_565;
    Bitmap bitmap = Bitmap.createBitmap(width, height, conf);

    new Thread(() -> {

        int cells_amount = 0;
        float cells_vertical = 0;
        float cells_horizontal = 0;

        cells_vertical = (float) height / CELL_SIZE;

        int y = 0;

        if (cells_vertical % 1 > 0) {
            y = Math.round(CELL_SIZE * -(cells_vertical % 1));
            cells_vertical = (int) (cells_vertical + 1);
        }

        cells_horizontal = (float) width / CELL_SIZE;

        int x = 0;

        if (cells_horizontal % 1 > 0) {
            x = Math.round(CELL_SIZE * -(cells_horizontal % 1));
            cells_horizontal = (int) (cells_horizontal + 1);
        }

        cells_amount = (int) (cells_horizontal * cells_vertical);

        Canvas c = new Canvas(bitmap);
        c.drawColor(Color.BLACK);

        int x_preserved = x;

        Paint textPaint = new Paint();
        textPaint.setColor(Color.parseColor("#EEEEEE"));

        for (int i = 0; i < cells_amount; i++) {
            Rect rect = new Rect(x, y, x + CELL_SIZE, y + CELL_SIZE);
            Paint framePaint = new Paint();
            framePaint.setColor(Color.parseColor("#1F1F1F"));
            framePaint.setStyle(Paint.Style.STROKE);
            framePaint.setStrokeWidth(1);

            c.drawRect(rect, framePaint);

            if (random.nextBoolean()) {
                String output = String.format(Locale.getDefault(), "%d", "+");

                int cx = (int) (x + (CELL_SIZE / 2) - (textPaint.measureText(output) / 2));
                int cy = (int) ((y + (CELL_SIZE / 2)) - ((textPaint.descent() + textPaint.ascent()) / 2));

                c.drawText(output, cx, cy, textPaint);
            }

            if (i % cells_horizontal == 0 && i >= cells_horizontal) {
                y += CELL_SIZE;
                x = x_preserved;
            } else {
                x += CELL_SIZE;
            }
        }
    }).start();

    canvas.drawBitmap(bitmap, 0, 0, null);
}

0 个答案:

没有答案