如何在android中的指定矩形中绘制文本?
作者:互联网
有没有一种方法可以在指定的矩形中绘制文本?
我正在使用直接绘制到画布(ImageView)
canvas.drawText(text,x,y,paint)
但这将整个文本放在一行中.我想用指定的(x,y),(x1,y1)限制包装文本.我不想使用textviews或任何其他视图.
我只想在图像上绘制文本.
有什么方法可以做到这一点?
提前致谢
解决方法:
首先,您必须确定文本大小.每个字符的宽度可以通过getTextWidths()获得,高度与文本大小相同.尝试估计初始文本大小,然后使用文本的高度和宽度调整最终值.
其次,您需要换行. Paint.getTextWidths()或Paint.breakText()都可以实现此目标.
编辑:添加代码示例.
public static class RectTextView extends View {
private int mWidth = 200;
private int mHeight = 100;
private String mText = "Hello world. Don't you know why, why you and I.";
private Paint mPaint;
private List<Integer> mTextBreakPoints;
public RectTextView(Context context) {
this(context, null);
}
public RectTextView(Context context, AttributeSet attrs) {
super(context, attrs);
mPaint = new Paint();
mPaint.setColor(Color.WHITE);
mPaint.setAntiAlias(true);
setSuitableTextSize();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(mWidth, mHeight);
}
@Override
protected void onDraw(Canvas canvas) {
int start = 0;
int x = 0;
int y = 0;
for (int point : mTextBreakPoints) {
y += mPaint.getTextSize();
canvas.drawText(mText, start, point, x, y, mPaint);
start = point;
}
}
private void setSuitableTextSize() {
int textSize = getEstimateTextSize();
for (; textSize > 0; textSize--) {
if (isTextSizeSuitable(textSize))
return;
}
}
private boolean isTextSizeSuitable(int size) {
mTextBreakPoints = new ArrayList<Integer>();
mPaint.setTextSize(size);
int start = 0;
int end = mText.length();
while (start < end) {
int len = mPaint.breakText(mText, start, end, true, mWidth,
null);
start += len;
mTextBreakPoints.add(start);
}
return mTextBreakPoints.size() * size < mHeight;
}
private int getEstimateTextSize() {
return (int) Math.sqrt(mWidth * mHeight / mText.length() * 2);
}
}
标签:drawtext,android-canvas,android 来源: https://codeday.me/bug/20191031/1976890.html