我想为我的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"/>
最佳答案 如果你想在XML中做这个比“Zephyr”approch完美适合这个但是如果想要动态地做这个你可以尝试一些像
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);
不确定,但在我的情况下,它水平显示渐变