我在自定义组件的绘制上动态添加位图。
现在谈到这一行:
line = Bitmap.createBitmap(line, 0, 0, line.getWidth(), 1);
我想将位图拉伸到组件的宽度。我在这里使用line.getWidth()
,但我希望有办法说this.getWidth
。不幸的是它在构造函数中,并且视图仍然不知道它的宽度。
以下是自定义组件的代码:
package com.adylitica.components;
import com.adylitica.activity.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
/**
* Defines a custom EditText View that draws lines between each line of text that is displayed.
*/
public class EditTextNotes extends EditText {
private Rect mRect;
private Bitmap line;
public static int nbLines = 0;
private SharedPreferences settings;
public EditTextNotes(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
line = BitmapFactory.decodeResource(context.getResources(), R.drawable.line_thin_new);
line = Bitmap.createBitmap(line, 0, 0, line.getWidth(), 1);
mRect = new Rect();
}
public EditTextNotes(Context context, AttributeSet attrs) {
super(context, attrs);
line = BitmapFactory.decodeResource(context.getResources(), R.drawable.line_thin_new);
line = Bitmap.createBitmap(line, 0, 0, line.getWidth(), 1);
mRect = new Rect();
}
public EditTextNotes(Context context) {
super(context);
line = BitmapFactory.decodeResource(context.getResources(), R.drawable.line_thin_new);
line = Bitmap.createBitmap(line, 0, 0, line.getWidth(), 1);
mRect = new Rect();
}
@Override
protected void onDraw(Canvas canvas) {
int count = getLineCount();
Rect r = mRect;
int baseline = 0;
int addSize = 0;
canvas.drawBitmap(line, 0, baseline, null);
for (int i = 0; i < count; i++) {
baseline = getLineBounds(i, r) + addSize;
canvas.drawBitmap(line, 0, baseline, null);
nbLines++;
}
super.onDraw(canvas);
}
}
PS:位图是9补丁。
感谢。
答案 0 :(得分:1)
你不应该在构造函数中进行测量。在自定义视图中,最好覆盖onSizeChanged()
。当您的视图以当前宽度和高度添加到视图层次结构时将调用它,如果您的视图调整大小,则会再次使用当前值和旧值。有关详细信息,请参阅[Handle Layout Events]。