自定义控件 渐变色的TextView

来源:互联网 发布:js 百度地图样式修改 编辑:程序博客网 时间:2024/05/22 18:37

0:
项目中遇到一个非常喜欢渐变色的UI,没办法只能上网查查,都不是很符合,看到一个是hongyang大神的,很炫,但是我想要不动的那种,所以结合自己查的资料写个不动的渐变色TextView
1:
直接上代码

public MyTextView(Context context) {        super(context);    }    public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        getAttrs(context, attrs);    }    public MyTextView(Context context, AttributeSet attrs) {        super(context, attrs);        getAttrs(context, attrs);    }    private void getAttrs(Context context, AttributeSet attrs){        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.mtv);        startcolor = ta.getColor(R.styleable.mtv_start_color, 0x00000000);        endcolor = ta.getColor(R.styleable.mtv_end_color, 0x00000000);        ta.recycle();    }    @Override    protected void onDraw(Canvas canvas) {        mViewWidth = getMeasuredWidth();        mPaint = getPaint();        String mTipText = getText().toString();        colors = new int[]{startcolor, endcolor};        mPaint.getTextBounds(mTipText, 0, mTipText.length(), mTextBound);        mLinearGradient = new LinearGradient(0, 0, mViewWidth, 0,                colors,                null, Shader.TileMode.REPEAT);        mPaint.setShader(mLinearGradient);        canvas.drawText(mTipText, getMeasuredWidth() / 2 - mTextBound.width() / 2, getMeasuredHeight() / 2 +   mTextBound.height()/2, mPaint);    }

重写了onDraw方法,主要是LinearGradient这个参数,colors是一个数组,里边放16进制的颜色值,这个值从构造方法中获得,通过getAttrs方法
values目录下 写一个attrs.xml

<resources>    <declare-styleable name="mtv">    <attr name="start_color" format="color"/>    <attr name="end_color" format="color"/>    </declare-styleable></resources>

然后再在布局文件中直接调用就好了

<com.konglsd.it.ggapp.Custom.MyTextView        android:clickable="true"        android:id="@+id/man"        mtv:start_color="#0A59C4"        mtv:end_color="#3C92FF"        android:textSize="16sp"        android:gravity="center"        android:text="男"        android:layout_width="match_parent"        android:layout_height="@dimen/y53" />

本来想写的详细点的,因为韦昕同学的原因懒得写了,就这样吧