我想要的输出:
带有自定义字体的小部件(主屏幕小部件)上的文本
我的问题:
- 不能在小部件的 TextView 上使用自定义字体(由于无法在小部件中直接访问 TextView,我们必须使用远程 View 来使用它们。)
所以我想使用 imageview 并使用 Canvas 在位图上绘制文本,然后在 imageview 上设置此位图。到目前为止,一切正常,但只有两件事。
我不知道,
如何让我的文本在垂直和水平方向上居中? (纵横是指纵横居中)
如何让我的文字填满位图的整个空间?
我正在使用以下代码在小部件上显示一些文本。
Bitmap bitmap = Bitmap.createBitmap(200, 200, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.YELLOW);
canvas.drawPaint(paint);
paint.setColor(Color.GREEN);
paint.setStyle(Style.FILL);
canvas.drawText("Test", 50, 50, paint);
下面是输出。
最佳答案
1- 在小部件的 textview 上设置字体运行时间
I dont know that either
2- 设置文本居中并填充容器
Please see the following code:
float size = 1.0f;
Bitmap bitmap = Bitmap.createBitmap(200, 200, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setColor(Color.YELLOW);
canvas.drawPaint(paint);
paint.setColor(Color.GREEN);
paint.setStyle(Style.FILL);
Rect rect = new Rect();
paint.getTextBounds("Test", 0, 4, rect);
float width = 1.0f;
while (width<200 && rect.height()<200)
{
size++;
paint.setTextSize(size);
width = paint.measureText("Test");
paint.getTextBounds("Test", 0, 4, rect);
}
size--;
paint.setTextSize(size);
canvas.drawText("Test", 100-width/2, 100+rect.height()/2, paint);
我试图附上屏幕截图,但它不允许我添加,因为我是新用户。(菜鸟 :P)
谢谢,
关于android - 在主屏幕小部件上使用 Canvas 绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10530781/