我正在尝试在位图中水平和垂直对齐文本,我阅读了几篇文章,但找不到解决方案。位图是一个简单的圆形图像。我发布了我的现有代码。大体上它能工作,但是文本并不完全居中,似乎有点偏左和偏上,我的意思是似乎需要添加一个偏移量将其向右和向下移动。
public static float convertDpToPixel(float dp, Context context) {
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float px = dp * (metrics.densityDpi / 160f);
return px;
}
v = (ImageView) findViewById(R.id.imageView1);
Bitmap b = BitmapFactory.decodeResource(getResources(),
R.drawable.marker).copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(b);
Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setARGB(255, 0, 0, 0);
textPaint.setTextAlign(Align.CENTER);
textPaint.setTypeface(Typeface.DEFAULT_BOLD);
textPaint.setTextSize(convertDpToPixel(9, this));
String text = "30";
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() +
textPaint.ascent()) / 2)) ;
canvas.drawText(text, xPos, yPos, textPaint);
v.setImageBitmap(b);