自定义控件 渐变色的TextView

本文介绍了一种自定义的Android TextView实现方案,该TextView能够显示静态渐变颜色文本。文章提供了详细的代码实现过程,包括如何使用LinearGradient设置颜色渐变效果,并展示了如何在XML布局文件中配置起始和结束颜色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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" />

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值