Reputation: 16798
I'm trying to implement custom view to display the text, but there is a problem with drawing the text (text is red, view's background is green):
The source code is on the pastebin.
Upvotes: 3
Views: 1780
Reputation: 6033
There are some problems with your onDraw() method. As you have not explicitly changed the text alignment, the text is by default aligned to left. In this mode the text is drawn from left(x) to right above the base line(y). In your code x = 0 and y = 0 and hence text start drawing from x=0 towards right and above the base line y = 0 and therefor your text is not visible. here is a modified version of your code:
public class FastTextView extends View {
private Context mContext;
private String mText = "";
private int mTextSize;
private Paint mPaint;
private int paddingLeft = 0;
private int paddingRight = 0;
private int paddingTop = 0;
private int paddingBottom = 0;
private int fontSize = 100;
public void setText(String text)
{
mText = text;
}
public FastTextView (Context context)
{
super(context);
initialize();
}
public FastTextView (Context context, AttributeSet attrs)
{
super(context, attrs);
initialize();
}
public void setPaddingLeft(int padding)
{
paddingLeft = padding;
}
public void setPaddingRight(int padding)
{
paddingRight = padding;
}
public void setPaddingBottom(int padding)
{
paddingBottom = padding;
}
public void setPaddingTop(int padding)
{
paddingTop = padding;
}
public void setFontSize(int size)
{
fontSize = size;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Rect rect = new Rect();
mPaint.getTextBounds(mText.toString(), 0, mText.length(), rect);
int width = Math.max(rect.width(), getSuggestedMinimumWidth()) + paddingLeft + paddingRight;
int height = Math.max(rect.height(), getSuggestedMinimumHeight()) + paddingTop + paddingBottom;
setMeasuredDimension(width, height);
}
/**
* Initialize the view
*/
private void initialize()
{
mContext = getContext();
mPaint = new Paint();
mPaint.setColor(Color.RED);
mPaint.setTextSize(fontSize);
mPaint.setTextAlign(Align.LEFT);
setBackgroundColor(Color.GREEN);
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
canvas.drawColor(Color.BLUE);
int x = paddingLeft;
int y = paddingTop + fontSize;
if (mText.length() > 0) {
canvas.drawText(mText, x, y-fontSize/4, mPaint);
}
}
}
Upvotes: 3
Reputation: 7585
Instead of drawing the text at the top of the view with(L 91) :
canvas.drawText(mText, 0, mText.length() - 1, 0, 0, mPaint);
try:
canvas.drawText(mText, 0, mText.length() - 1, 0, canvas.getHeight(), mPaint);
Note that the align settings are stored in the Paint
variable. So you should probably change that if your text still isn't drawn correctly.
Upvotes: 2