本文共 3615 字,大约阅读时间需要 12 分钟。
MaskFilter类可以为Paint分配边缘效果。
对MaskFilter的扩展可以对一个Paint边缘的alpha通道应用转换。Android包含了下面几种MaskFilter:要应用一个MaskFilter,可以使用setMaskFilter方法,并传递给它一个MaskFilter对象
BlurMaskFilter:
package com.soyoungboy.customview.widget;import android.annotation.TargetApi;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.BlurMaskFilter;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Rect;import android.os.Build;import android.util.AttributeSet;import android.view.View;import com.example.customview.R;@TargetApi(Build.VERSION_CODES.HONEYCOMB)public class BlurMaskFilterView extends View { private Paint mPaint; private Bitmap mBitmap; private Bitmap mAlphaBmp; public BlurMaskFilterView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public BlurMaskFilterView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public BlurMaskFilterView(Context context) { super(context); init(); } /** * 进行初始化操作 */ private void init() { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { setLayerType(View.LAYER_TYPE_SOFTWARE, null); } mPaint = new Paint(); mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); mAlphaBmp = mBitmap.extractAlpha(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 宽度 int width = 200; // 高度 int height = width * mAlphaBmp.getHeight() / mAlphaBmp.getWidth(); // 绘制红色阴影,首先将画笔设置为红色 mPaint.setColor(Color.RED); // 就是添加内外发光效果 mPaint.setMaskFilter(new BlurMaskFilter(10, BlurMaskFilter.Blur.NORMAL)); // 绘制阴影在矩形框里面 左上角坐标 10,10,右下角坐标width,height canvas.drawBitmap(mAlphaBmp, null, new Rect(10, 10, width, height), mPaint); // 绘制原图像 mPaint.setMaskFilter(null); canvas.drawBitmap(mBitmap, null, new Rect(0, 0, width, height), mPaint); }}
效果图:
mPaint.setMaskFilter(new BlurMaskFilter(10, BlurMaskFilter.Blur.INNER));
效果图:
mPaint.setMaskFilter(new BlurMaskFilter(10, BlurMaskFilter.Blur.OUTER));
效果图:
mPaint.setMaskFilter(new BlurMaskFilter(10, BlurMaskFilter.Blur.SOLID));
使用EmbossMaskFilter
修改onDraw()里面方法:
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 宽度 int width = 200; // 高度 int height = width * mAlphaBmp.getHeight() / mAlphaBmp.getWidth(); //设置光源的方向 float[] direction = new float[] { 1, 1, -1 }; // 设置环境光亮度 float light = 1f; // 选择要应用的反射等级 float specular = 6; // 向mask应用一定级别的模糊 float blur = 3.5f; EmbossMaskFilter emboss = new EmbossMaskFilter(direction, light, specular, blur); mPaint.setMaskFilter(emboss); mPaint.setColor(Color.BLUE); // 绘制阴影在矩形框里面 左上角坐标 10,10,右下角坐标width,height canvas.drawBitmap(mAlphaBmp, null, new Rect(10, 10, width, height), mPaint); }
效果图:
转载地址:http://saezo.baihongyu.com/