2

我的自定义视图中有下一个扩展 EditText 的代码:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

                int count = getLineCount();
                Canvas cvs= new Canvas();
                Drawable dr = this.getBackground();
                Rect r = mRect;
                Paint paint = mPaint;
                mTextPaint.setTextSize(this.getTextSize());
                Paint PaintText = mTextPaint;

                for (int i = 0; i < count; i++) {
                    int baseline = getLineBounds(i, r);
                    cvs.drawText(Integer.toString(i+1), r.left, baseline + 1, PaintText);
                    cvs.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint); 
                }
                cvs.drawLine(PaintText.measureText(Integer.toString(count)), this.getTop(), PaintText.measureText(Integer.toString(count)), this.getBottom(), paint);
                dr.setBounds(0, 0, this.getRight(), this.getBottom());
                dr.draw(cvs);
                this.setBackgroundDrawable(dr);
            }

为什么这个观点的背景上什么都没有?

4

3 回答 3

5
protected void onDraw(Canvas canvas) {
    Bitmap bitmap = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.ARGB_8888);
    int count = getLineCount();
    Canvas cvs= new Canvas(bitmap);
    cvs.drawColor(Color.rgb(245, 245, 245));
    Rect r = mRect;
    Paint paint = mPaint;
    mTextPaint.setTextSize(this.getTextSize());
    Paint PaintText = mTextPaint;

    for (int i = 0; i < count; i++) {
        int baseline = getLineBounds(i, r);
        cvs.drawText(Integer.toString(i+1), 2, baseline + 1, PaintText);
        cvs.drawLine(2, baseline + 1, r.right, baseline + 1, paint); 
    }

    cvs.drawLine(PaintText.measureText(Integer.toString(count))+3, this.getTop(), PaintText.measureText(Integer.toString(count))+3, this.getBottom(), paint);

    this.setBackgroundDrawable(new BitmapDrawable(getContext().getResources(), bitmap));
    this.setPadding((int) (PaintText.measureText(Integer.toString(count))+7),3,3,3); 
    super.onDraw(canvas);
}
于 2011-03-27T08:17:36.317 回答
3

我认为您正在尝试做一些可以更容易完成的事情。但是,您的代码不起作用,因为:

  1. 您没有Bitmap为您的Canvas对象设置 a 。
  2. 我认为您想将 的内容移动Canvas到,Drawable但实际上您的代码执行了相反的操作。Drawable实际上,您在Canvas对象上绘制。试试这个:
    位图位图 = Bitmap.createBitmap(this.getWidth(), this.getHeight(),
        Bitmap.Config.ARGB_8888);
    画布 cvs = 新画布(位图);
    // 你的绘图没有 dr.setBounds() 和 dr.draw()
    this.setBackgroundDrawable(
        新的 BitmapDrawable(getContext().getResources(), bitmap));
于 2011-03-26T20:54:31.607 回答
1

您不需要创建新的 Canvas 对象。onDraw 为您创建一个并将其设置在自己的位图中。只需使用参数中指定的画布名称(在本例中为画布)。

每次创建视图或调用 invalidate() 时都会调用 onDraw。在您的 onDraw() 方法中,您正在创建一个新的画布对象。如果您将此代码用于任何图形密集的事物(例如游戏),那么您就是在泄漏内存。即使您只绘制一次视图,这也不是最好的方法。使用 onDraw() 参数中提供的画布。

于 2011-03-28T04:53:43.690 回答