画布drawtext多线居中

时间:2017-01-22 17:49:51

标签: android canvas

我需要在水平和垂直居中的位图中绘制文本,调整文本大小以覆盖所有空间。问题是文本与\n是多行的。这是我目前的代码:

private int determineMaxTextSize(String str, float maxWidth) {
        int size = 0;
        if (TextUtils.isEmpty(str))
            return 0;
        Paint paint = new Paint();
        do {
            paint.setTextSize(++size);
        } while (paint.measureText(str) < maxWidth);
        return size > 0 ? size - 1 : 0;
    }

private void drawText(String text, int textColor, int bckColor) {
    TextPaint paint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
    int max = Integer.MAX_VALUE;
    String[] tokens = text.split("\n");
    for (String s : tokens) {
        int m = determineMaxTextSize(s, params.width);
        if (m > 0 && m < max)
            max = m;
    }
    paint.setTextSize(max);
    paint.setColor(textColor);
    paint.setTextAlign(Paint.Align.CENTER);
    Bitmap b = Bitmap.createBitmap(params.width + 1, params.height + 1, Bitmap.Config.ARGB_8888);
    b.eraseColor(bckColor);
    Canvas canvas = new Canvas(b);
    Rect r = new Rect();
    int xPos = canvas.getWidth() / 2;
    int yPos = (canvas.getHeight() / 2);
    for (String s : tokens) {
        if (s.equals("\n"))
            s = " ";
        paint.getTextBounds(s, 0, s.length(), r);
        canvas.drawText(s, xPos, yPos, paint);
        yPos += Math.abs(r.height());
    }
    setImageBitmap(b);
}

此代码几乎可以使用,但文本从中心开始。

1 个答案:

答案 0 :(得分:2)

这是一个迟到的答案,所以如果不再需要我道歉但在寻找答案后我决定用一些数学来解决这个问题。

为了使我的多行文本居中,我取画布的宽度,减去文本的宽度,然后除以2.然后将此数字用作drawText方法的x偏移量。

以下是我的完整示例:

public static Bitmap textAsBitmap(String text, float textSize, int textColor, Context mContext) {
    Paint paint = new Paint(ANTI_ALIAS_FLAG);
    int pixel = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, textSize, mContext.getResources().getDisplayMetrics());

    String[] str = text.split(",");

    paint.setTextSize(pixel);
    paint.setTypeface(FontUtils.getRalewayExtraBold(mContext));
    paint.setColor(textColor);
    paint.setTextAlign(Paint.Align.LEFT);
    float baseline = -paint.ascent(); // ascent() is negative
    int width = (int) (paint.measureText(text) + 0.0f); // round

    int height = (int) (baseline + paint.descent() + 0.0f);
    Bitmap image = Bitmap.createBitmap((width/str.length)+10, (height*str.length), Bitmap.Config.ARGB_8888);

    Canvas canvas = new Canvas(image);

    for (int i = 0; i < str.length; i++){
        //Center text here
        float textOffset = (canvas.getWidth()-paint.measureText((str[i])))/2;
        canvas.drawText(str[i], textOffset, ((i+1)*baseline), paint);
    }

    return image;
}