gpt4 book ai didi

android - 如何缩放字符以适合 Rect 以绘制文本?

转载 作者:太空宇宙 更新时间:2023-11-03 10:54:32 28 4
gpt4 key购买 nike

我有一个 Rect 的 ArrayList,以及我想绘制到各个 Rect 中的字符,每个 Rect 一个字符。

我想拉伸(stretch)文本以适应给定的 Rect,填充 Rect,因此我可以使用 canvas.drawText() 来绘制文本。

我想我需要一些 setTextSize() 和 setTextScaleX() 的组合,但我不知道从哪里开始设置参数。如何让我的角色适合 Rects?

希望之前有人解决过这个问题并能指出正确的方向。

最佳答案

我最终用 approach使用 getTextBounds确定要使用的文本的大小和比例:

// Adjust text size to fill rect
paint.setTextSize(100);
paint.setTextScaleX(1.0f);
// ask the paint for the bounding rect if it were to draw this text
Rect bounds = new Rect();
paint.getTextBounds(words[i], 0, words[i].length(), bounds);
// get the height that would have been produced
int h = bounds.bottom - bounds.top;
// figure out what textSize setting would create that height of text
float size = (((float)(rect.height())/h)*100f);
// and set it into the paint
paint.setTextSize(size);
// Now set the scale.
// do calculation with scale of 1.0 (no scale)
paint.setTextScaleX(1.0f);
// ask the paint for the bounding rect if it were to draw this text.
paint.getTextBounds(words[i], 0, words[i].length(), bounds);
// determine the width
int w = bounds.right - bounds.left;
// calculate the baseline to use so that the entire text is visible including the descenders
int text_h = bounds.bottom-bounds.top;
int baseline =bounds.bottom+((rect.height()-text_h)/2);
// determine how much to scale the width to fit the view
float xscale = ((float) (rect.width())) / w;
// set the scale for the text paint
paint.setTextScaleX(xscale);
canvas.drawText(words[i], frame.left + rect.left * scaleX, frame.top + rect.bottom * scaleY - baseline, paint);

关于android - 如何缩放字符以适合 Rect 以绘制文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7864697/

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