2013-07-03 30 views
0

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

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); 
} 

任何建议将非常感激。 在此先感谢。

回答

0

这里有三个(加一)建议:

  • 创建和初始化Paint对象只有一次,不是每一个你做的绘图时间。
  • 预加载并保留您绘制的位图,如果它始终是相同的。
  • 你可以直接创建自定义Drawable类,并在其中使用draw()方法做你的绘画。

  • 激进(可能不适用于您的需求):在您的布局中,使用位图制作一个ImageView,并在其上放置一个TextView作为文本。

+0

好的,谢谢你的建议。我会试试看。 – jmetran