作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我最初是从下面这段代码开始的:
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;
}
它按预期工作,背景图像在那里,文本也在那里,只是文本对于屏幕来说太长了,我需要以某种方式将其换行。
然后我研究了 TextPaint
和 StaticLayout
来处理这段代码的多行问题。
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/
我是一名优秀的程序员,十分优秀!