我自己找到了解决方案。
您可以计算字符串在画布上绘制后的宽度。然后您知道在更改颜色后继续在画布上绘制文本的位置。
package com.example;
import android.app.Activity;
import android.content.Context;
import android.graphics.*;
import android.os.Bundle;
import android.view.View;
public class MyActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SampleView(this));
}
private static class SampleView extends View {
public SampleView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.WHITE);
String blackText = "black";
String redText = " red";
Paint mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTextSize(30);
mPaint.setTypeface(Typeface.create(Typeface.SERIF,
Typeface.ITALIC));
float canvasWidth = canvas.getWidth();
float blackTextWidth = mPaint.measureText(blackText);
float sentenceWidth = mPaint.measureText(blackText + redText);
float startPositionX = (canvasWidth - sentenceWidth) / 2;
mPaint.setTextAlign(Paint.Align.LEFT);
canvas.translate(0, 80);
mPaint.setColor(Color.BLACK);
canvas.drawText(blackText, startPositionX, 0, mPaint);
mPaint.setColor(Color.RED);
canvas.drawText(redText, startPositionX + blackTextWidth, 0,mPaint);
}
}
}