【发布时间】:2016-09-07 10:37:37
【问题描述】:
我已经进行了几次测试以将文本放置在画布上的给定位置,并得出结论 drawText() 无法正常工作。 (我的示例代码和屏幕截图将显示。)如果可能,请给我一个建议如何克服这个问题。
如果有任何文本(在我的示例中为“123”),我可以正确获取文本的大小。但是,定位(主要是水平方向)并不准确。更糟糕的是,这种现象并非对所有角色都相同。例如。如果文本以“A”开头,它会按预期工作。
我从我的屏幕截图中附上了两个区域。带有“123”的显示文本如何向右偏移。带有“A12”的显示定位正确时的外观。我的代码用给定的文本尺寸绘制了一个灰色的控制矩形。人们应该期望文本完全出现在这个框架中。但事实并非如此。有了这个问题,就不可能准确地设置图纸中的任何文字。
package com.pm.pmcentertest;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.View;
public class Draw extends View {
public Paint myPaint;
public Draw(Context context) {
super(context);
myPaint = new Paint();
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.CYAN);
// The text shall appear in the lower left corner
int x = 0;
int y = canvas.getHeight();
// We use a large text size for demonstration
String Text = "123";
myPaint.setTextSize(400);
// We get the dimensions of the text
Rect bounds = new Rect();
myPaint.getTextBounds(Text, 0, Text.length(), bounds);
// Now we draw a rectangle for the area in which the text should appear
// using the TextBounds values
myPaint.setColor(Color.parseColor("GREY"));
canvas.drawRect(x, y - bounds.height(), x + bounds.width(), y, myPaint);
// Now we draw the text to the same position
myPaint.setColor(Color.parseColor("WHITE"));
canvas.drawText(Text, x, y, myPaint);
}
}
【问题讨论】:
-
你想达到什么目的?