如何写为本多种颜色的文本到画布画布、为本、如何写、文本

2023-09-05 00:49:57 作者:墨绿色眼眸

我是从一个线程写入的画布。

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

我的问题开始,当我有我想写到画布多彩色SpannableStringBuilder,我不知道如何做到这一点。 SpannableStringBuilder拥有的drawText()方法,我已经无法使用。还是有写一个字符串到画布上,其中一些字母有不同的颜色一些其他的方法?

My problem start when I have a multi colored SpannableStringBuilder which I want to write to the canvas, and 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);

    }
  }
}
 
精彩推荐
图片推荐