我正在写一个线程的画布.
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()方法,我一直无法使用.或者是否有其他方法将字符串写入画布,其中一些字母具有不同的颜色?
解决方法
我自己找到了解决方案.
您可以计算字符串在画布上绘制后的宽度.然后你知道在改变颜色之后还在哪里继续向画布绘制文本.
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,mPaint); mPaint.setColor(Color.RED); canvas.drawText(redText,startPositionX + blackTextWidth,mPaint); } } }