I dynamically add a bitmap on the draw of a custom component.
Now when it comes to this line :
line = Bitmap.createBitmap(line, 0, 0, line.getWidth(), 1);
I’d like to stretch the bitmap to the width of the component. Here I use line.getWidth() but I wish there was a way to say this.getWidth. Unfortunately it’s in the constructor and the view still doesn’t know its width.
Here is the code of the custom component :
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: the bitmap is 9patched.
Thanks.
You should not be doing your measuring in the constructor. In a custom view, it is best to override
onSizeChanged(). It will be called when your view is added to the view hierarchy with the current width and height, and again with current and old values if your view is ever resized. See [Handle Layout Events] for details.