我正在写一个帖子的画布。
public void draw(Canvas canvas) {
Paint p = new Paint();
p.setAntiAlias(true);
p.setTextSize(30);
p.setColor(Color.WHITE);
p.setTextAlign(Paint.Align.CENTER);
canvas.drawText("Centered", xCentre, yCentre, p);
}
我的问题从我想要写入画布的多色SpannableStringBuilder
开始,我不知道如何做到这一点。 SpannableStringBuilder
有drawText()
方法我无法使用。或者是否有其他方法将字符串写入画布,其中一些字母具有不同的颜色?
答案 0 :(得分:20)
我自己找到了解决方案。
您可以计算字符串在画布上绘制后的宽度。然后你知道在改变颜色之后还在哪里继续将颜色绘制到画布上。
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);
}
}
}