一:文字颜色的渐变通过自定义控件实现
首先需要继承系统的textview,重写onDraw()方法。
利用LinearGradient 实现线性渐变,
LinearGradient lg=new LinearGradien(0,0,100,100,Color.RED,Color.BLUE,Shader.TileMode.MIRROR);
参数一为渐变起初点坐标x位置,参数二为y轴位置,参数三和四分辨对应渐变终点,最后参数为平铺方式,这里设置为镜像
Gradient是基于Shader类,所以我们通过Paint的setShader方法来设置这个渐变,代码如下: mPaint.setShader(lg);
注意:
除了定义开始颜色和结束颜色以外还可以定义,多种颜色组成的分段渐变效果
LinearGradient shader = new LinearGradient(0, 0, endX, endY, new int[]{startColor, midleColor, endColor},new float[]{0 , 0.5f, 1.0f}, TileMode.MIRROR);
其中参数new int[]{startColor, midleColor, endColor}是参与渐变效果的颜色集合,
其中参数new float[]{0 , 0.5f, 1.0f}是定义每个颜色处于的渐变相对位置,
这个参数可以为null,如果为null表示所有的颜色按顺序均匀的分布
private LinearGradient mLinearGradient;
private Paint mPaint;
private int mViewWidth = 0;
private Rect mTextBound = new Rect();
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
mViewWidth = getMeasuredWidth();
mPaint = getPaint();
String mTipText = getText().toString();
mPaint.getTextBounds(mTipText, 0, mTipText.length(), mTextBound);
mLinearGradient = new LinearGradient(0, 0, mViewWidth, 0,
new int[]{0xFF266459, 0xFF14A49F},
null, Shader.TileMode.REPEAT);
mPaint.setShader(mLinearGradient);
canvas.drawText(mTipText, getMeasuredWidth() / 2 - mTextBound.width() / 2, getMeasuredHeight() / 2 + mTextBound.height() / 2, mPaint);
}
最后在xml中引用自定义的控件:
<com.example.chenhaiyan2.colorchange.MyTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="这里将发生颜色的渐变"
android:textSize="30dp" />
二:实现背景颜色渐变
shape定义形状,gradient定义该形状里面的内容为渐变色,startColor表示开始颜色,centerColor表示中间颜色,endColor表示结束颜色。
angle表示方向角度。当angle=0时,渐变色是从左向右。 然后逆时针方向转,当angle=90时为从下往上。
具体代码:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="0"
android:centerColor="#ffffff"
android:centerX="0.5"
android:centerY="0.5"
android:endColor="#14A49F"
android:startColor="#266459"
android:type="linear" />
<corners android:radius="5dp" />
</shape>
引用:
android:background=”@drawable/shape”
到这里两种渐变都可以实现。
参考:
http://blog.youkuaiyun.com/qaz13177_58_/article/details/7852389