android實現文字漸層效果和歌詞進度的效果

來源:互聯網
上載者:User

android實現文字漸層效果和歌詞進度的效果

要用TextView使用漸層色,那我們就必須要瞭解LinearGradient(線性漸層)的用法。

LinearGradient的參數解釋

LinearGradient也稱作線性渲染,LinearGradient的作用是實現某一地區內顏色的線性漸層效果,看源碼你就知道他是shader的子類。

它有兩個建構函式

public LinearGradient(float x0, float y0, float x1, float y1, int color0, int color1, Shader.TileMode tile)public LinearGradient (float x0, float y0, float x1, float y1, int[] colors, float[] positions, Shader.TileMode tile);

其中,參數x0表示漸層的起始點x座標;參數y0表示漸層的起始點y座標;參數x1表示漸層的終點x座標;參數y1表示漸層的終點y座標 ;color0表示漸層開始顏色;color1表示漸層結束顏色;參數tile表示平鋪方式。

Shader.TileMode有3種參數可供選擇,分別為CLAMP、REPEAT和MIRROR:

CLAMP的作用是如果渲染器超出原始邊界範圍,則會複製邊緣顏色對超出範圍的地區進行著色

REPEAT的作用是在橫向和縱向上以平鋪的形式重複渲染位元影像

MIRROR的作用是在橫向和縱向上以鏡像的方式重複渲染位元影像

LinearGradient的簡單使用

先實現文字效果的水平漸層:

Shader shader_horizontal= new LinearGradient(btWidth/4, 0, btWidth, 0, Color.RED, Color.GREEN, Shader.TileMode.CLAMP);                tv_text_horizontal.getPaint().setShader(shader_horizontal);


再實現文字的垂直漸層效果:

Shader shader_vertical=new LinearGradient(0, btHeight/4, 0, btHeight, Color.RED, Color.GREEN, Shader.TileMode.CLAMP);                tv_text_vertical.getPaint().setShader(shader_vertical);


接下來來實現文字的顏色動態漸層效果:<喎?http://www.bkjia.com/kf/ware/vc/" target="_blank" class="keylink">vcD4NCjxwcmUgY2xhc3M9"brush:java;">import android.content.Context;import android.graphics.Canvas;import android.graphics.LinearGradient;import android.graphics.Matrix;import android.graphics.Paint;import android.graphics.Shader;import android.util.AttributeSet;import android.widget.TextView;/** * Created on 2016/3/13. */public class GradientHorizontalTextView extends TextView { private LinearGradient mLinearGradient; private Matrix mGradientMatrix;//漸層矩陣 private Paint mPaint;//畫筆 private int mViewWidth = 0;//textView的寬 private int mTranslate = 0;//平移量 private boolean mAnimating = true;//是否動畫 private int delta = 15;//移動增量 public GradientHorizontalTextView(Context ctx) { this(ctx,null); } public GradientHorizontalTextView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (mViewWidth == 0) { mViewWidth = getMeasuredWidth(); if (mViewWidth > 0) { mPaint = getPaint(); String text = getText().toString(); int size; if(text.length()>0) { size = mViewWidth*2/text.length(); }else{ size = mViewWidth; } mLinearGradient = new LinearGradient(-size, 0, 0, 0, new int[] { 0x33ffffff, 0xffffffff, 0x33ffffff }, new float[] { 0, 0.5f, 1 }, Shader.TileMode.CLAMP); //邊緣融合 mPaint.setShader(mLinearGradient);//設定漸層 mGradientMatrix = new Matrix(); } } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mAnimating && mGradientMatrix != null) { float mTextWidth = getPaint().measureText(getText().toString());//獲得文字寬 mTranslate += delta;//預設向右移動 if (mTranslate > mTextWidth+1 || mTranslate<1) { delta = -delta;//向左移動 } mGradientMatrix.setTranslate(mTranslate, 0); mLinearGradient.setLocalMatrix(mGradientMatrix); postInvalidateDelayed(30);//重新整理 } }}

實現歌詞進度效果

Canvas 作為繪製文本時,使用FontMetrics對象,計算位置的座標。它的思路和java.awt.FontMetrics的基本相同。
FontMetrics對象它以四個基本座標為基準,分別為:

FontMetrics.top
FontMetrics.ascent
FontMetrics.descent
FontMetrics.bottom

// FontMetrics對象  FontMetrics fontMetrics = textPaint.getFontMetrics();    String text = "abcdefghijklmnopqrstu";    // 計算每一個座標  float baseX = 0;    float baseY = 100;    float topY = baseY + fontMetrics.top;    float ascentY = baseY + fontMetrics.ascent;    float descentY = baseY + fontMetrics.descent;    float bottomY = baseY + fontMetrics.bottom;  

下面是具體實現代碼:

import android.content.Context;import android.graphics.Bitmap;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.PorterDuff;import android.graphics.PorterDuffXfermode;import android.graphics.RectF;import android.util.AttributeSet;import android.view.View;/** * Created  on 2016/3/13. */public class SongTextView extends View {    private int postIndex;    private Paint mPaint;    private int delta = 15;    private float mTextHeight;    private float mTextWidth;    private String mText="夢 裡 面 看 我 七 十 二 變";    private PorterDuffXfermode xformode;    public SongTextView(Context ctx)    {        this(ctx,null);    }    public SongTextView(Context context, AttributeSet attrs) {        this(context, attrs, 0);    }    public SongTextView(Context context,  AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        init();    }    public void init()    {        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);        xformode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);        mPaint.setColor(Color.CYAN);        mPaint.setTextSize(60.0f);        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);        mPaint.setXfermode(null);        mPaint.setTextAlign(Paint.Align.LEFT);        //文字精確高度        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();        mTextHeight = fontMetrics.bottom-fontMetrics.descent-fontMetrics.ascent;        mTextWidth  = mPaint.measureText(mText);    }    /**      *計算 控制項的寬高      */    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {      final  int mWidth;      final  int mHeight;        /**         * 設定寬度         */        int widthMode = MeasureSpec.getMode(widthMeasureSpec);        int widthSize = MeasureSpec.getSize(widthMeasureSpec);        if (widthMode == MeasureSpec.EXACTLY)// match_parent , accurate            mWidth = widthSize;        else        {            // 由圖片決定的寬            int desireByImg = getPaddingLeft() + getPaddingRight()                    + getMeasuredWidth();            if (widthMode == MeasureSpec.AT_MOST)// wrap_content                mWidth = Math.min(desireByImg, widthSize);             else                mWidth = desireByImg;        }        /***         * 設定高度         */        int   heightMode = MeasureSpec.getMode(heightMeasureSpec);        int   heightSize = MeasureSpec.getSize(heightMeasureSpec);        if (heightMode == MeasureSpec.EXACTLY)// match_parent , accurate            mHeight = heightSize;         else        {            int desire = getPaddingTop() + getPaddingBottom()                    + getMeasuredHeight();            if (heightMode == MeasureSpec.AT_MOST)// wrap_content                mHeight = Math.min(desire, heightSize);             else                mHeight = desire;        }        setMeasuredDimension( mWidth,  mHeight);    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        Bitmap srcBitmap = Bitmap.createBitmap(getMeasuredWidth(),getMeasuredHeight(), Bitmap.Config.ARGB_8888);        Canvas srcCanvas = new Canvas(srcBitmap);        srcCanvas.drawText(mText, 0, mTextHeight, mPaint);        mPaint.setXfermode(xformode);        mPaint.setColor(Color.RED);        RectF rectF = new RectF(0,0,postIndex,getMeasuredHeight());        srcCanvas.drawRect(rectF, mPaint);        canvas.drawBitmap(srcBitmap, 0, 0, null);        init();        if(postIndex

ProgressBar實現歌詞播放效果

然後接下來的這種歌詞播放進度效果是2張圖片實現的,忘記是哪個那裡看來的,壓根以前也沒有想過還可以這麼樣的實現。
只需要準備2張圖即可:

  

看見沒就是2張圖片,一張作為背景圖一張作為進度圖,是不是感覺很神奇,然後放入ProgressBar

 

再加上代碼動態改變progress就能實現進度的變化了:

 ProgressBar pb1= (ProgressBar) findViewById(R.id.pb1); //設定捲軸可見 setProgressBarIndeterminateVisibility(true); progress=pb1.getProgress();//擷取初始進度 timer=new Timer(); task=new TimerTask() { @Override public void run() { progress+=10; if(progress>100){ progress=0; } handler.sendEmptyMessage(0); } }; timer.schedule(task,1000,300);

實現及進度的改變:

Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); pb1.setProgress(progress); }}; @Override protected void onDestroy() { super.onDestroy(); timer=null; task=null; handler.removeCallbacksAndMessages(null); }

效果也是不錯的:

能力有限,感覺寫一篇部落格要弄好久,網速卡的一筆,就寫到這了,其實項目裡面也沒有用到,休息2天了也寫點東西,就覺得還是要學一點東西作為備用知識。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.