开发者

How to write centered multi-colored text to a canvas?

I am writing to a canvas from a thread.

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);
}

My problem start when I have a multi colored SpannableStringBuilder which I want to write to the canvas, a开发者_如何学Cnd I have no idea how to do this. SpannableStringBuilder has a drawText() method which I have been unable to use. Or is there some other method to write a string to a canvas where some of the letters have a different color?


I found the solution to this myself.

You can calculate the width that the string will have after being drawn on the canvas. Then you know where too continue to paint text to the canvas after having changed color.

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);

    }
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜