【问题标题】:How to create horizontal gradient for text color of AppCompatButton in android如何在android中为AppCompatButton的文本颜色创建水平渐变
【发布时间】:2017-09-25 05:46:19
【问题描述】:

我想为我的AppCompatButton 生成水平文本颜色渐变。我能够通过

完成垂直文本颜色渐变
val signInBtn = view.findViewById<AppCompatButton>(R.id.btn_sign_in)
val textShader = LinearGradient(0f, 0f, 0f, signInBtn.textSize,
            ContextCompat.getColor(context, R.color.gradient_start),
            ContextCompat.getColor(context, R.color.gradient_end), TileMode.CLAMP)
signInBtn.paint.shader = textShader

我已尝试更改 x2 值,但似乎没有任何效果。任何帮助将不胜感激。

这是我的按钮 xml 布局

<android.support.v7.widget.AppCompatButton
    android:id="@+id/btn_sign_in"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginEnd="@dimen/big"
    android:layout_marginStart="@dimen/big"
    android:layout_marginTop="@dimen/big"
    android:background="@color/white"
    android:text="@string/sign_in"
    android:textAllCaps="false"
    android:fadingEdge="horizontal"
    android:scrollHorizontally="true"
    android:textColor="@color/white"/>

【问题讨论】:

    标签: android button shader linear-gradients


    【解决方案1】:

    如果您想在 XML 中执行此操作,那么“Zephyr”方法非常适合此操作,但如果您想动态执行此操作,您可以尝试类似

    Button theButton = (Button)findViewById(R.id.thebutton);
    ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
        @Override
        public Shader resize(int width, int height) {
            LinearGradient lg = new LinearGradient(0, 0, 0, theButton.getHeight(),
                new int[] { 
                    Color.LIGHT_GREEN, 
                    Color.WHITE, 
                    Color.MID_GREEN, 
                    Color.DARK_GREEN }, //substitute the correct colors for these
                new float[] {
                    0, 0.45f, 0.55f, 1 },
                Shader.TileMode.REPEAT);
             return lg;
        }
    };
    PaintDrawable p = new PaintDrawable();
    p.setShape(new RectShape());
    p.setShaderFactory(sf);
    theButton.setBackgroundDrawable((Drawable)p);
    

    不确定,但在我的情况下,它会水平显示渐变

    【讨论】:

    • 我不是要改变背景颜色,我想改变按钮的文字颜色渐变
    • @zephyr 再次仔细阅读问题,我想要水平渐变,而不是垂直
    • @Samuel Robert,查看我编辑的答案,希望对您有所帮助。
    猜你喜欢
    • 2019-08-27
    • 1970-01-01
    • 2015-03-06
    • 2016-03-02
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 2020-05-28
    • 2023-03-21
    相关资源
    最近更新 更多