Android 中漂亮的描边文字

Beautiful Stroked Text in Android

我知道如何使用自定义视图(EditText 或 TextView)对文本进行描边,但我无法实现像这个漂亮的东西,这是使用 Photoshop 完成的。是的,它也有外部阴影。

到目前为止我所做的是调整笔画宽度和笔画连接样式。但是,如果我增加笔画宽度,笔画就会出现在整个文本中。 据我搜索,有一个名为 MagicTextView 的库,但它也无法给出上述结果。

更新:我已经根据@pskink 的建议进行了调整。现在可以了。但是我不能再拖了。如果我拖动那个 EditText,就会出现一些像这样的奇怪线条。

代码如下:

@Override public void onDraw(Canvas canvas) {
  final int x = this.getLeft();
  final int y = this.getBottom();

  mText = this.getText().toString();

  p.setStrokeWidth(30);
  p.setStyle(Style.STROKE);
  p.setStrokeJoin(Join.ROUND);
  p.setColor(0xffffffff);

  canvas.drawText(mText, x, y, p);

  p.setStyle(Style.FILL);
  p.setColor(0xff000000);

  canvas.drawText(mText, x, y, p);
}

However, if I increase the stroke width, the stroke took place the whole text.

如果问题是笔划居中,而您希望它位于文本之外,请参阅:Android Paint stroke width positioning

You must precalculate the desired width and height according to your stroke.

我建议尝试使用非常粗体的字体。在下图中,white 笔划将以 red 线为中心(这将是每个 black字母).

回应您的更新

If I drag that EditText, there is some weird lines showed up.

该行可能是将焦点放在 EditText 上的结果。您可以显式地移除焦点:Android: Force EditText to remove focus?

或者,您可以设置焦点的样式(如果它不会对您的其余部分产生不利影响,则可以是不可见的 UI):How to change the color of a focused EditText when using "android:Theme.Holo.Light"?

经过几个小时的调整,我已经修复了更新问题中所述的奇怪线路问题。我想我应该post这里作为答案。

@Override public void onDraw(Canvas canvas) {
    mText = this.getText().toString();

    p.setStyle(Style.STROKE);
    p.setStrokeJoin(Join.ROUND);
    p.setShadowLayer(10, 1, 1, 0xcfcccccc);

    canvas.drawText(mText, 0, getLineHeight(), p);

    p.clearShadowLayer();
    p.setStrokeWidth(35);
    p.setStrokeJoin(Join.ROUND);
    p.setStyle(Style.STROKE);
    p.setColor(0xffffffff);

    canvas.drawText(mText, 0, getLineHeight(), p);

    p.setStyle(Style.FILL);
    p.setColor(0xff000000);

    canvas.drawText(mText, 0, getLineHeight(), p);
    canvas.translate(xPos, yPos);
}

xPos 和 yPos 是来自 ACTION_MOVE onTouch 事件的 x 和 y 值。我们需要为 canvas 文本添加行高作为 Y。