【问题标题】:center text vertically and horizontally with canvas使用画布垂直和水平居中文本
【发布时间】: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


    【解决方案1】:

    正如@Merlevede 所说,如果你将 textPaint 对齐到 CENTER,你只需要这样做:

    canvas.drawText(
        text,
        canvas.getWidth() / 2,
        ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)),
        textPaint
    );
    

    【讨论】:

      【解决方案2】:

      问题是您目前没有考虑文本的宽度和高度。如果你的文字是“你好”或“这是一个字符串”,你只是一视同仁,那就错了。

      您需要计算文本的宽度和高度,然后将文本位置移动这些距离的一半。

      例如垂直居中:

      Rect r = new Rect();
      paint.getTextBounds(text, 0, text.length(), r);
      yPos += (Math.abs(r.height()))/2;    // or maybe -= instead of +=, depends on your coordinates
      

      我希望这会带你进入正确的方向。

      编辑: 原点是根据绘图中的对齐设置来解释的。你正在使用

       textPaint.setTextAlign(Align.CENTER);
      

      所以你可能不需要做任何计算来水平居中(这意味着对于水平原点你应该使用你已经拥有的代码)。

       int xPos = (canvas.getWidth() / 2);
      

      【讨论】:

      • 现在更好一点的代码是: int xPos = (canvas.getWidth() / 2) - ((r.width())/2); int yPos = (canvas.getHeight() / 2) + ((r.height())/2);但是 x 不再对齐,现在我将文本移到了左侧。
      【解决方案3】:

      对于水平位置: xPos = (canvas.getWidth() / 2) - (widthofthetext)/2;

      对于垂直: yPos = (canvas.getHeight() / 2) - (heightofthetext)/2;

      我是通过电话发布的,对于未经测试的答案,我深表歉意。让我知道它是否会起作用。

      【讨论】:

      • 请看我对之前回复的评论。
      猜你喜欢
      • 2015-09-25
      • 1970-01-01
      • 2012-03-14
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      • 2013-07-27
      • 2012-01-01
      相关资源
      最近更新 更多