zoukankan      html  css  js  c++  java
  • Android Textview实现文字颜色渐变效果

    最近做应用的时候遇到一个需求,一行文字的颜色需要一个渐变效果

    如上所有 从左到有逐渐变化,自己写了一个demo实现上述效果

    package com.huwei.example.test;
    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.LinearGradient;
    import android.graphics.Paint;
    import android.graphics.Rect;
    import android.graphics.Shader;
    import android.util.AttributeSet;
    import android.widget.TextView;
     
    public class MyTextView extends TextView {
     
        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[] {  0xFF429321, 0xFFB4EC51 },
                    null, Shader.TileMode.REPEAT);
            mPaint.setShader(mLinearGradient);
            canvas.drawText(mTipText, getMeasuredWidth() / 2 - mTextBound.width() / 2, getMeasuredHeight() / 2 +   mTextBound.height()/2, mPaint);
        }
     
    }

    核心实现是用了一个LinaerGradient 给paint设置一个LinaerGradient  

    利用这个LinaerGradient  也可以实现一些其他类似效果,如以下颜色渐变的线条,颜色渐变的图片等

  • 相关阅读:
    机器视觉行业分析
    lua sample code analysis
    My GPU info from "GPU Caps Viewer"
    网页hack程序编写
    debug redmine send email
    如何下载web资源
    看国内网络电视解决方案2
    看国内网络电视解决方案
    babel-polyfill使用与性能优化
    升级NGINX支持HTTP/2服务端推送
  • 原文地址:https://www.cnblogs.com/huwei0814/p/5382039.html
Copyright © 2011-2022 走看看