gpt4 book ai didi

java - 在 Canvas 顶部绘制多行文本

转载 作者:行者123 更新时间:2023-11-30 03:03:23 25 4
gpt4 key购买 nike

所以我最初是从下面这段代码开始的:

private Bitmap writeTextOnDrawable(int drawableId, String text) {

Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId);
Bitmap alteredBitmap = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());
Canvas canvas = new Canvas(alteredBitmap);
Paint paint = new Paint();
canvas.drawBitmap(bm, 0, 0, paint);
paint.setColor(Color.WHITE);
paint.setTextSize(150f);
canvas.drawText(text, 100, 1000, paint);

return alteredBitmap;
}

它按预期工作,背景图像在那里,文本也在那里,只是文本对于屏幕来说太长了,我需要以某种方式将其换行。

然后我研究了 TextPaintStaticLayout 来处理这段代码的多行问题。

private Bitmap writeTextOnDrawable(int drawableId, String text) {

Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId);
Bitmap alteredBitmap = Bitmap.createBitmap(bm.getWidth(), bm.getHeight(), bm.getConfig());
Canvas canvas = new Canvas(alteredBitmap);
TextPaint tp = new TextPaint();
canvas.save();
tp.setColor(Color.WHITE);
tp.setTextSize(150f);
tp.setTextAlign(Align.CENTER);
tp.setAntiAlias(true);
StaticLayout sl = new StaticLayout("" + text, tp,
canvas.getWidth(), Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
canvas.translate(100, 1000);
sl.draw(canvas);

return alteredBitmap;
}

这根本不起作用。我的背景图片现在不见了,它什么也没有显示。文本没有像以前那样居中。唯一的好处是文本现在是多行的。

有谁知道为什么文本改变了它的初始起点以及为什么 Canvas 的背景图像消失了?任何帮助将不胜感激。

最佳答案

由于 canvas.translate() 函数,您的文本从初始起点偏移。我不知道为什么你的背景图片消失了,因为你从来没有提到位图的使用位置(方式)。如果您希望文本出现在 View 的左上角,这里是一个示例。

创建 ImageView (iv) 并将其位图设置为:

iv.setImageBitmap(writeTextOnDrawable(drawableId, text));

现在你的函数:

private Bitmap writeTextOnDrawable(int drawableId, String text) {

Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId);
// Create your ImageView-size bitmap
Bitmap alteredBitmap = Bitmap.createBitmap(iv.getWidth(), iv.getHeight(), bm.getConfig());
Canvas canvas = new Canvas(alteredBitmap);
TextPaint tp = new TextPaint();
tp.setColor(Color.WHITE);
tp.setTextSize(24);
tp.setAntiAlias(true);
StaticLayout sl = new StaticLayout(text, tp,
iv.getWidth(), Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
sl.draw(canvas);

return alteredBitmap;
}

之后,您应该会在背景图片上看到多行文本。

关于java - 在 Canvas 顶部绘制多行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22210016/

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