【问题标题】:Android TextView shadow doesn't work when Radius set to 0当 Radius 设置为 0 时,Android TextView 阴影不起作用
【发布时间】:2015-10-17 08:39:40
【问题描述】:

我需要在标题上绘制阴影,没有任何模糊,如下图所示: text with shadow, shadowRadius = 0

我的问题是,一旦我将 shadowRadius 设置为 0,阴影就不再出现了。

这是我在 style.xml 中使用的代码

<style name="navigationTitleWithShadow">
    <item name="android:textAllCaps">true</item>
    <item name="android:textColor">@color/navigationTitleForegroundColor</item>
    <item name="android:shadowColor">@color/navigationTitleShadowColor</item>
    <item name="android:shadowDx">1</item>
    <item name="android:shadowDy">1</item>
    <item name="android:shadowRadius">0</item>
</style>

在布局中:

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"

    android:text="@string/menuTableViewController_navigationTitle"
    android:textAppearance="@style/navigationTitleWithShadow" />

知道如何拥有这个 0 shadowRadius 吗?

【问题讨论】:

  • 我不确定,但通过阅读文档我看到 android:shadowRadius 必须是浮点值。我不知道是否可以将值设置为 0。也许尝试 0.0
  • 谢谢!我尝试了 0.0、0.1、0.5,只要我的值低于 1,就没有阴影。
  • 在我的情况下,0.1f 为我工作(我正在将阴影应用于绘制对象)。

标签: android textview shadow


【解决方案1】:

我找到了一个解决方案,继承 TextView,覆盖方法 onDraw()。这是我的代码:

@Override
protected void onDraw(Canvas canvas) {
    //super.onDraw(canvas);

    if ( getShadowColor() != 0 && getShadowRadius() == 0 ) {

        Paint paint = this.getPaint();
        paint.setColor(getShadowColor());

        paint.setTextAlign(Paint.Align.CENTER);

        int xPos = (canvas.getWidth() / 2);
        int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() +
                paint.ascent()) / 2));

        // Draw the shadow text first, so it appears below
        canvas.drawText(getText().toString().toUpperCase(), xPos + getShadowDx(), yPos + getShadowDy(), paint);

        paint.setColor(getCurrentTextColor());

        // Draw the main text on top of it
        canvas.drawText(getText().toString().toUpperCase(), xPos, yPos, paint);

    } else {
        super.onDraw(canvas);
    }

}

效果很好,虽然我不知道为什么需要 setTextAlign,但没有它我的文本会错位,在右边。

【讨论】:

    【解决方案2】:

    虽然TextView.shadowRadius 中没有说明,但Paint.setShadowLayer 的描述指出

    如果半径为0,则阴影层被移除。

    将阴影完全隐藏在文本后面似乎是个好主意,但由于阴影可以偏移并且文本可以是半透明的,因此可以隐藏想要的阴影。

    使用 0.1f 的最小模糊是不一样的,但在我的情况下是可行的。

    paint.setShadowLayer(
        max(blur, 0.1f),
        dx,
        dy,
        color
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-04
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多