0

我想问一下如何提高这些代码的性能。基本上它所做的是绘制一个 BitmapDrawable 并将其用作 ImageView 的可绘制对象,然后将其放置在 TableView 的 TableRow 上。

private void drawTableData() {
    TableLayout table = new TableLayout(this);

    BitmapDrawable bm;
    TableRow row = new TableRow(this);
    String rowData = "A1;A2;A3;A4;A5;A6;A7;A8;A9;A10;A11;A12;";
    String[] tmpRowData = rowData.split("\\;");

    for (String str : tmpRowData) {
        ImageView img = new ImageView(this);
        bm = writeOnDrawable(R.drawable.seat_check_icon, str);
        img.setImageDrawable(bm);
        img.setLayoutParams(new TableRow.LayoutParams(20, 20));
        row.addView(img);
    }
    table.addView(row, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}

public BitmapDrawable writeOnDrawable(int drawableId, String text) {
    Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId).copy(Bitmap.Config.ARGB_8888, true);
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setTypeface(Typeface.DEFAULT_BOLD);
    paint.setStyle(Style.FILL);
    paint.setColor(txtColor);
    paint.setTextSize((float) 14);

    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);
    int height = bounds.bottom + bounds.height();
    int width = bounds.left + bounds.width();

    float canvasWidth = bm.getWidth();
    float canvasHeight = bm.getHeight();
    float startPositionX = (canvasWidth - width) / 2;
    float startPositionY = (canvasHeight + height) / 2;

    Canvas canvas = new Canvas(bm);
    canvas.drawText(text, startPositionX, startPositionY, paint);
    return new BitmapDrawable(this.getResources(), bm);
}

任何建议将不胜感激。提前致谢。

4

1 回答 1

0

Here are three (plus one) suggestions:

  • Create and initialize your Paint object only once, not every time you do the drawing.
  • Preload and keep the bitmap you draw upon, if it's always the same one.
  • You could directly create your custom Drawable class and in it's draw() method do your painting.

  • Radical (may not apply to your needs): In your layout, make one ImageView with the bitmap and put a TextView on top of it for the text.

于 2013-07-03T06:37:23.837 回答