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以上的的系统会默认开启硬件加速器,致使部分方法没法使用。