我的自定义视图中有下一个代码,它扩展了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);
}
为什么这个观点的背景上什么都没有?
答案 0 :(得分: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);
}
答案 1 :(得分:3)
我认为你正在尝试做一些可以做得更容易的事情。但是,您的代码不起作用,因为:
Bitmap
对象设置Canvas
。Canvas
的内容移至Drawable
,但实际上您的代码执行相反的操作。实际上,您在Drawable
对象上绘制Canvas
。试试这个:Bitmap bitmap = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.ARGB_8888); Canvas cvs = new Canvas(bitmap); // Your drawing stuff without dr.setBounds() and dr.draw() this.setBackgroundDrawable( new BitmapDrawable(getContext().getResources(), bitmap));
答案 2 :(得分:1)
您无需创建新的Canvas对象。 onDraw为您创建一个并将其设置在自己的位图中。只需使用参数中指定的画布名称(在本例中为canvas)。
每次创建视图或调用invalidate()时都会调用onDraw。在onDraw()方法中,您将创建一个新的canvas对象。如果您使用此代码进行任何图形密集的操作(如游戏),那么您就会泄漏内存。即使您只绘制一次视图,这也不是最好的方法。使用onDraw()参数中提供的画布。