如何写为本多种颜色的文本到画布 [英] How to write centered multi-colored text to a canvas

查看:201
本文介绍了如何写为本多种颜色的文本到画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

    }
  }
}

这篇关于如何写为本多种颜色的文本到画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆