gpt4 book ai didi

android - 自定义类 TextView 和文本绘图

转载 作者:太空宇宙 更新时间:2023-11-03 13:00:26 25 4
gpt4 key购买 nike

我正在尝试实现自定义 View 来显示文本,但是绘制文本时出现问题(文本为红色, View 的背景为绿色):

enter image description here

源代码在pastebin .

最佳答案

您的 onDraw() 方法存在一些问题。由于您没有明确更改文本对齐方式,因此文本默认左对齐。在这种模式下,文本在基线 (y) 上方从左 (x) 绘制到右。在您的代码中 x = 0 和 y = 0,因此文本开始从 x=0 向右和基线 y = 0 上方绘制,因此您的文本不可见。这是您的代码的修改版本:

公共(public)类 FastTextView 扩展 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);
}
}

关于android - 自定义类 TextView 和文本绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12413052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com