[英]Android Center text on canvas
我正在嘗試使用下面的代碼顯示文本。 問題是文本沒有水平居中。 當我為drawText
設置坐標時,它會在此位置設置文本的底部。 我希望繪制文本,以便文本也水平居中。
這是進一步顯示我的問題的圖片:
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
//canvas.drawRGB(2, 2, 200);
Paint textPaint = new Paint();
textPaint.setARGB(200, 254, 0, 0);
textPaint.setTextAlign(Align.CENTER);
textPaint.setTypeface(font);
textPaint.setTextSize(300);
canvas.drawText("Hello", canvas.getWidth()/2, canvas.getHeight()/2 , textPaint);
}
請嘗試以下操作:
Paint textPaint = new Paint();
textPaint.setTextAlign(Paint.Align.CENTER);
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ;
//((textPaint.descent() + textPaint.ascent()) / 2) is the distance from the baseline to the center.
canvas.drawText("Hello", xPos, yPos, textPaint);
以Paint.getTextBounds() 為中心:
private Rect r = new Rect();
private void drawCenter(Canvas canvas, Paint paint, String text) {
canvas.getClipBounds(r);
int cHeight = r.height();
int cWidth = r.width();
paint.setTextAlign(Paint.Align.LEFT);
paint.getTextBounds(text, 0, text.length(), r);
float x = cWidth / 2f - r.width() / 2f - r.left;
float y = cHeight / 2f + r.height() / 2f - r.bottom;
canvas.drawText(text, x, y, paint);
}
Paint.Align.CENTER並不意味着文本的參考點垂直居中。 參考點始終在基線上。 那么,為什么不使用Paint.Align.LEFT呢? 無論如何,您必須計算參考點。
Paint.descent()有一個缺點,它不考慮真實的文本。 Paint.descent()檢索相同的值,無論文本是否包含帶有下降的字母。 這就是我使用r.bottom的原因。
我有一些問題與Canvas.getHeight()如果API <16,這就是為什么我使用Canvas.getClipBounds(矩形)來代替。 (不要使用Canvas.getClipBounds().getHeight()因為它為Rect分配內存。)
出於性能原因,您應該在onDraw()中使用對象之前分配對象。 由於drawCenter()將在onDraw()內被調用,因此對象Rect r在這里被預先分配為一個字段。
我嘗試將兩個頂級答案的代碼放入我自己的代碼中(2015 年 8 月),並制作了一個屏幕截圖來比較結果:
文本應在紅色填充矩形內居中。 我的代碼生成白色文本,其他兩個代碼一起生成灰色文本(它們實際上相同,重疊)。 灰色文本有點太低,右邊有兩個。
這是我進行測試的方式:
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
class MyView extends View {
private static String LABEL = "long";
private static float TEXT_HEIGHT_RATIO = 0.82f;
private FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(0, 0);
private Rect r = new Rect();
private Paint paint = new Paint();
private Paint rectPaint = new Paint();
public MyView(Context context) {
super(context);
}
private void drawTextBounds(Canvas canvas, Rect rect, int x, int y) {
rectPaint.setColor(Color.rgb(0, 0, 0));
rectPaint.setStyle(Paint.Style.STROKE);
rectPaint.setStrokeWidth(3f);
rect.offset(x, y);
canvas.drawRect(rect, rectPaint);
}
// andreas1724 (white color):
private void draw1(Canvas canvas, Paint paint, String text) {
paint.setTextAlign(Paint.Align.LEFT);
paint.setColor(Color.rgb(255, 255, 255));
canvas.getClipBounds(r);
int cHeight = r.height();
int cWidth = r.width();
paint.getTextBounds(text, 0, text.length(), r);
float x = cWidth / 2f - r.width() / 2f - r.left;
float y = cHeight / 2f + r.height() / 2f - r.bottom;
canvas.drawText(text, x, y, paint);
drawTextBounds(canvas, r, (int) x, (int) y);
}
// Arun George (light green color):
private void draw2(Canvas canvas, Paint textPaint, String text) {
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setColor(Color.argb(100, 0, 255, 0));
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2));
canvas.drawText(text, xPos, yPos, textPaint);
}
// VinceStyling (light blue color):
private void draw3(Canvas yourCanvas, Paint mPaint, String pageTitle) {
mPaint.setTextAlign(Paint.Align.LEFT);
mPaint.setColor(Color.argb(100, 0, 0, 255));
r = yourCanvas.getClipBounds();
RectF bounds = new RectF(r);
bounds.right = mPaint.measureText(pageTitle, 0, pageTitle.length());
bounds.bottom = mPaint.descent() - mPaint.ascent();
bounds.left += (r.width() - bounds.right) / 2.0f;
bounds.top += (r.height() - bounds.bottom) / 2.0f;
yourCanvas.drawText(pageTitle, bounds.left, bounds.top - mPaint.ascent(), mPaint);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
int margin = 10;
int width = w - 2 * margin;
int height = h - 2 * margin;
params.width = width;
params.height = height;
params.leftMargin = margin;
params.topMargin = margin;
setLayoutParams(params);
paint.setTextSize(height * TEXT_HEIGHT_RATIO);
paint.setAntiAlias(true);
paint.setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD_ITALIC));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.rgb(255, 0, 0));
draw1(canvas, paint, LABEL);
draw2(canvas, paint, LABEL);
draw3(canvas, paint, LABEL);
}
}
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
FrameLayout container = new FrameLayout(this);
container.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
container.addView(new MyView(this));
setContentView(container);
}
}
垂直對齊很困難,因為文本下降和上升發生了,很多人使用Paint.getTextBounds()來檢索 TextWidth 和 TextHeight,但它並沒有使文本居中。 這里我們可以使用Paint.measureText()來計算TextWidth,TextHeight我們簡單的用descent和ascent做減法,然后我們得到了最接近TextSize的方法,接下來的工作對彼此來說還算輕松。
// the Paint instance(should be assign as a field of class).
Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setTextSize(getResources().getDimension(R.dimen.btn_textsize));
// the display area.
Rect areaRect = new Rect(0, 0, 240, 60);
// draw the background style (pure color or image)
mPaint.setColor(Color.BLACK);
yourCanvas.drawRect(areaRect, mPaint);
String pageTitle = "文字小說";
RectF bounds = new RectF(areaRect);
// measure text width
bounds.right = mPaint.measureText(pageTitle, 0, pageTitle.length());
// measure text height
bounds.bottom = mPaint.descent() - mPaint.ascent();
bounds.left += (areaRect.width() - bounds.right) / 2.0f;
bounds.top += (areaRect.height() - bounds.bottom) / 2.0f;
mPaint.setColor(Color.WHITE);
yourCanvas.drawText(pageTitle, bounds.left, bounds.top - mPaint.ascent(), mPaint);
順便說一下,我們強烈推薦使用RectF而不是Rect因為位置需要更准確的值,根據我的經驗,RectF 在 xhdpi 設備上只完成了一個像素的頂部和底部偏差,Rect 將是兩個更多。
您的代碼在視圖的中心繪制文本基線的中心。 為了在某些時候,X,Y居中文本,你需要計算文本的中心,並把那個在點。
此方法將以點 x, y 為中心繪制文本。 如果您將它傳遞到視圖的中心,它將繪制居中的文本。
private void drawTextCentered(String text, int x, int y, Paint paint, Canvas canvas) {
int xPos = x - (int)(paint.measureText(text)/2);
int yPos = (int) (y - ((textPaint.descent() + textPaint.ascent()) / 2)) ;
canvas.drawText(text, xPos, yPos, textPaint);
}
我發現居中文本的最佳解決方案如下:
textPaint.setTextAlign(Paint.Align.CENTER);
//textPaint is the Paint object being used to draw the text (it must be initialized beforehand)
float textY=center.y;
float textX=center.x;
// in this case, center.x and center.y represent the coordinates of the center of the rectangle in which the text is being placed
canvas.drawText(text,textX,textY,textPaint); `
適合我使用: textPaint.textAlign = Paint.Align.CENTER with textPaint.getTextBounds
private fun drawNumber(i: Int, canvas: Canvas, translate: Float) {
val text = "$i"
textPaint.textAlign = Paint.Align.CENTER
textPaint.getTextBounds(text, 0, text.length, textBound)
canvas.drawText(
"$i",
translate + circleRadius,
(height / 2 + textBound.height() / 2).toFloat(),
textPaint
)
}
結果是:
我創建了一個方法來簡化這個:
public static void drawCenterText(String text, RectF rectF, Canvas canvas, Paint paint) {
Paint.Align align = paint.getTextAlign();
float x;
float y;
//x
if (align == Paint.Align.LEFT) {
x = rectF.centerX() - paint.measureText(text) / 2;
} else if (align == Paint.Align.CENTER) {
x = rectF.centerX();
} else {
x = rectF.centerX() + paint.measureText(text) / 2;
}
//y
metrics = paint.getFontMetrics();
float acent = Math.abs(metrics.ascent);
float descent = Math.abs(metrics.descent);
y = rectF.centerY() + (acent - descent) / 2f;
canvas.drawText(text, x, y, paint);
Log.e("ghui", "top:" + metrics.top + ",ascent:" + metrics.ascent
+ ",dscent:" + metrics.descent + ",leading:" + metrics.leading + ",bottom" + metrics.bottom);
}
rectF就是你要畫文字的區域,就是這樣。 細節
這對我有用:
paint.setTextAlign(Paint.Align.CENTER);
int xPos = (newWidth / 2);
int yPos = (newHeight / 2);
canvas.drawText("Hello", xPos, yPos, paint);
如果有人發現任何問題,請告訴我
就我而言,我不必將文本放在畫布中間,而是放在旋轉的輪子中。 雖然我必須使用此代碼才能成功:
fun getTextRect(textSize: Float, textPaint: TextPaint, string: String) : PointF {
val rect = RectF(left, top, right, bottom)
val rectHeight = Rect()
val cx = rect.centerX()
val cy = rect.centerY()
textPaint.getTextBounds(string, 0, string.length, rectHeight)
val y = cy + rectHeight.height()/2
val x = cx - textPaint.measureText(string)/2
return PointF(x, y)
}
然后我從 View 類調用這個方法:
private fun drawText(canvas: Canvas, paint: TextPaint, text: String, string: String) {
val pointF = getTextRect(paint.textSize, textPaint, string)
canvas.drawText(text, pointF!!.x, pointF.y, paint)
}
在您的油漆屬性中使用它:
textPaint.setTextAlign(Paint.Align.CENTER);
如果我們使用靜態布局
mStaticLayout = new StaticLayout(mText, mTextPaint, mTextWidth,
Layout.Alignment.ALIGN_CENTER, 1.0f, 0, true);
Layout.Alignment.ALIGN_CENTER這可以解決問題。 靜態布局還有很多其他優點。
參考: Android 文檔
將這些添加到您的 onDraw 方法中:
paint.setColor(getContext().getResources().getColor(R.color.black));
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText("Text", (float) getHeight() / 2f, (float) getWidth() / 2f, paint);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.