我想在我的布局中绘制一些全屏幕文本,问题是我可以得到一个准确的点。这是我编码的:
DisplayMetrics display = getResources().getDisplayMetrics();
int width = display.widthPixels;
String data_azi = DateFormat.getDateTimeInstance().format(new Date());
cnv.drawText(data_azi, width - p.measureText(data_azi), 40,p);
答案 0 :(得分:1)
您需要提前测量并在绘图时使用该测量。例如,您可以在初始时调用measureText()
。此方法测量当前日期的宽度,并将测量宽度增加20%。
private final Rect mBounds = new Rect();
private final Date mDate = new Date();
private void measureText(final Paint p){
final String dummy = DateFormat.getDateTimeInstance().format(mDate);
p.getTextBounds(dummy, 0, dummy.length(), mBounds);
final int inset = (int) (mBounds.width()*0.1f); //add safety margin
mBounds.inset(-inset, 0);
}
然后你这样绘制:
mDate.setTime(System.currentTimeMillis());
String data_azi = DateFormat.getDateTimeInstance().format(mDate);
cnv.drawText(data_azi, width - mBounds.width(), mBounds.height(),p);
还要确保您的绘画对象左对齐p.setTextAlign(Align.LEFT);