【发布时间】:2014-03-31 10:15:18
【问题描述】:
我正在尝试水平和垂直对齐位图中的文本,我阅读了几篇帖子,但找不到解决方案。位图是一个简单的圆形图像。我发布我当前的代码。或多或少可以工作,但文本不是完全居中,它似乎有点在左边,有点在顶部,我的意思是我似乎必须添加一个偏移量才能将它移动到右侧和底部。
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);
【问题讨论】:
标签: android android-canvas drawtext