gpt4 book ai didi

Android canvas drawText 文本的y位置

转载 作者:IT老高 更新时间:2023-10-28 22:02:47 26 4
gpt4 key购买 nike

我正在使用 Canvas 创建一个带有一些背景和一些文本的 Drawable。可绘制对象用作 EditText 内的复合可绘制对象。

文本是通过 Canvas 上的 drawText() 绘制的,但在某些情况下,绘制文本的 y 位置确实存在问题。在这种情况下,部分字符会被截断(参见图片链接)。

没有定位问题的字符:

http://i50.tinypic.com/zkpu1l.jpg

有定位问题的字符,文本包含“g”、“j”、“q”等:

http://i45.tinypic.com/vrqxja.jpg

您可以在下面找到重现该问题的代码 fragment 。

有专家知道如何确定 y 位置的正确偏移吗?

public void writeTestBitmap(String text, String fileName) {
// font size
float fontSize = new EditText(this.getContext()).getTextSize();
fontSize+=fontSize*0.2f;
// paint to write text with
Paint paint = new Paint();
paint.setStyle(Style.FILL);
paint.setColor(Color.DKGRAY);
paint.setAntiAlias(true);
paint.setTypeface(Typeface.SERIF);
paint.setTextSize((int)fontSize);
// min. rect of text
Rect textBounds = new Rect();
paint.getTextBounds(text, 0, text.length(), textBounds);
// create bitmap for text
Bitmap bm = Bitmap.createBitmap(textBounds.width(), textBounds.height(), Bitmap.Config.ARGB_8888);
// canvas
Canvas canvas = new Canvas(bm);
canvas.drawARGB(255, 0, 255, 0);// for visualization
// y = ?
canvas.drawText(text, 0, textBounds.height(), paint);

try {
FileOutputStream out = new FileOutputStream(fileName);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (Exception e) {
e.printStackTrace();
}
}

最佳答案

我认为假设 textBounds.bottom = 0 可能是错误的。对于那些降序字符,这些字符的底部可能低于 0(这意味着 textBounds.bottom > 0)。你可能想要这样的东西:

canvas.drawText(text, 0, textBounds.top, paint);//而不是 textBounds.height()

如果您的 textBounds 从 +5 到 -5,并且您在 y=height (10) 处绘制文本,那么您只会看到文本的上半部分。

关于Android canvas drawText 文本的y位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10606410/

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