android - TextView 中的 LinearGradient 和透明颜色

标签 android textview transparency gradient

我用了Linear Gradient在TextView中设置渐变色,发现很有意思的情况。为了设置 TextView 渐变,我使用了这段代码:

int c1 = getResources().getColor(R.color.test1);
int c2 = getResources().getColor(R.color.test2);
Shader shader = new LinearGradient(0, 0, 0, status.getTextSize(),
                                   new int[]{c1, c2},
                                   new float[]{0, 1}, Shader.TileMode.CLAMP);
status.getPaint().setShader(shader);

我玩了一点颜色

  1. 仅设置 c1=green 和 c2-transparent
    <color name="test1">#ff00ff00</color>
    <color name="test2">#000000ff</color>
    

enter image description here

  1. 仅设置 c2=blue 和 c1-transparent
    <color name="test1">#0000ff00</color>
    <color name="test2">#ff0000ff</color>
    

enter image description here

所以在第二种情况下我看不到透明。

有人可以解释一下这个渐变生成器的性质吗?

更新: 感谢@Romain Guy 的回答。我玩了更多渐变,几乎得到了我想要的:

    Shader shader = new LinearGradient(0, 0, 0, status.getTextSize(),
            new int[]{c1, c2, colour, colour},
            new float[]{0.2f, 0.7f, 0.699f, 1}, Shader.TileMode.CLAMP);

和 status.setIncludeFontPadding();

正确: enter image description here

错误: enter image description here

正如您所看到的,纯色和渐变颜色的中心边框会根据填充值发生变化。

我们能否计算渐变边框的浮点值以准确获取 TextView 中字符的中心? 我认为这将取决于 FontType。

最佳答案

半透明效果就在那里。问题是你从 0 开始渐变,它在文本之上。您可能应该考虑 TextView 的填充和/或您正在使用的字体的 FontMetrics。

关于android - TextView 中的 LinearGradient 和透明颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16628091/

相关文章:

html - 如何应用具有透明到白色渐变的淡出文本效果?

带有 Alpha channel 的 WPF 3D 纹理

swift - NSRectFill 和 NSBezierPath(rect).fill 有什么区别

android - 在 Android WebView 中定位和平移/缩放 Flot 图表

android - View 不包含卡片 View 中的内容

android-如何扩展FragmentActivity和actionbaractivity

java - 在运行时添加字体资源

java - Android Kotlin `.replaceRange` 不会替换 SpannableString 中的文本

java - 如何让一个简单的 Android 应用程序在按下按钮后显示一个数字

java - Dagger Hilt 测试错误 - 错误 : cannot find symbol @ScopeMetadata, @QualifierMetadata