MaskFilter的做用就是在畫的上面糊上一層,然 被糊上的一層是什麼樣的就要使用其子類BlurMaskFilter、EmbossMaskFilter來具體實現。BlurMaskFilter是將paint變得模糊,EmbossMaskFilter是將paint變得有凸起的效果即浮雕的效果。canvas
做用:模糊掉指定半徑的邊緣ide
構造函數:BlurMaskFilter(float radius, BlurMaskFilter.Blur style)函數
radius 從原始mask擴展模糊的半徑. Must be > 0 style 要使用的模糊屬性
內部類:BlurMaskFilter.Blur 模糊屬性區分爲INNER(內部) 、 NORMAL(正常)、 OUTER(外部)、 SOLID(立方體)code
相關代碼:圖片
public MaskFilterCustomView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mPaint = new Paint(); mPaint.setColor(Color.RED); bFilter = new BlurMaskFilter(100, BlurMaskFilter.Blur.NORMAL);//INNER、OUTER、SOLID mPaint.setMaskFilter(bFilter); mRect = new Rect(150, 150, 1000, 1000); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawRect(mRect, mPaint); //關閉硬件加速器 setLayerType(View.LAYER_TYPE_SOFTWARE, null); }
運行結果:it
構造函數:EmbossMaskFilter(float[] direction, float ambient, float specular, float blurRadius)io
direction :使用三維座標來肯定光源的方向 ambient :背景光係數(0~1) specular :鏡面反射係數 blurRadius :模糊半徑
相關代碼:擴展
public MaskFilterCustomView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mPaint = new Paint(); mPaint.setColor(Color.RED); mRect = new Rect(150, 150, 500, 500); float[] direction = new float[]{10f,10f,10f};//方向 第一種 //float[] direction = new float[]{100f,10f,10f};第二種 //float[] direction = new float[]{100f,100f,10f};第三種 float ambient = 0.5f;//方向 float specular = 10; float blurRadius = 50; embossMaskFilter = new EmbossMaskFilter(direction,ambient,specular,blurRadius); mPaint.setMaskFilter(embossMaskFilter); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawRect(mRect, mPaint); // canvas.drawPath(mPath,mPaint); //關閉硬件加速器 setLayerType(View.LAYER_TYPE_SOFTWARE, null); }
運行結果:硬件
注意: 若是沒有添加setLayerType(View.LAYER_TYPE_SOFTWARE, null),以上效果則沒法出現。構造函數
緣由:4.0以上的的系統會默認開啓硬件加速器,致使部分方法沒法使用。