Shader類的使用
下面有大部分內容摘自http://blog.csdn.net/t12x3456/article/details/10418901
方法:
1. boolean getLoaclMatrix(Matrix localM); 如果shader有一個非本地的矩陣將返回true.
localM:如果不爲null將被設置爲shader的本地矩陣.
2. void setLocalMatrix(Matrix localM);
設置shader的本地矩陣,如果localM爲空將重置shader的本地矩陣。
Shader的直接子類:
BitmapShader : 位圖圖像渲染
LinearGradient : 線性渲染
RadialGradient : 環形渲染
SweepGradient : 掃描漸變渲染/梯度渲染
ComposeShader : 組合渲染,可以和其他幾個子類組合起來使用
是不是很像Animation及其子類的關係(AlphaAnimation,RotateAnimation,ScaleAnimation,TranslateAnimation, AnimationSet)
既有具體的渲染效果,也有渲染效果的組合
下面說下Shader的使用步驟:
1. 新建一個Shader對象
2. 通過Paint的setShader方法給畫筆Paint添加渲染對象
3.設置渲染對象的屬性
4.繪製時使用這個Paint對象
核心代碼:
子View重寫View的onSizeChanged方法,此方法主要完成一些初始化工作,大家可能有疑問爲什麼不把初始化代碼放到構造方法中呢?你想啊,萬一你的這個自定義View處於某種需求導致尺寸改變了,那麼你獲取的viewWidth肯定不再是之前的值了,所以我們應該檢測自定義View的尺寸是否發生過變化,要是有變化,系統會自動調用onSizeChange方法,從而把初始化工作重新執行一遍。
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// TODO Auto-generated method stub
super.onSizeChanged(w, h, oldw, oldh);
if(viewWidth==0){
viewWidth = getMeasuredWidth();
if(viewWidth>0){
mPaint = new Paint();
mPaint.setColor(getResources().getColor(android.R.color.holo_blue_dark));
mPaint.setStyle(Paint.Style.FILL);
mLinearGradient = new LinearGradient(0, 200, 200, 0, new int[]{Color.BLUE,Color.WHITE,Color.YELLOW,Color.RED}, null, TileMode.CLAMP);
mPaint.setShader(mLinearGradient);
mMatrix = new Matrix();
}
}
}
重寫View的onDraw方法
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
if(mMatrix!=null){
mTranslate += <span style="font-family: mceinline;">viewWidth</span><span style="font-family: mceinline;">/10;</span>
if(mTranslate>400){
mTranslate = -<span style="font-family: mceinline;">viewWidth</span>;
}
mMatrix.setTranslate(mTranslate, 0);
mLinearGradient.setLocalMatrix(mMatrix);
canvas.drawCircle(200, 200, 200, mPaint);
postInvalidateDelayed(100);
}
}