Paint常用方法
mPaint = new Paint();
初始化画笔
mPaint.setColor(Color.RED);// 设置颜色
颜色可以为0xffffff形式,或者通过Color.parseColor("#ffffff");
mPaint.setARGB(255, 255, 255, 0);
设置 Paint对象颜色,范围为0~255
mPaint.setAlpha(200);
设置alpha不透明度,范围为0~255
mPaint.setAntiAlias(true); // 抗锯齿
mPaint.setDither(true);//设置防抖动
mPaint.setStyle(Paint.Style.FILL);
Paint.Style.FILL:填充;Paint.Style.STROKE:描边;Paint.Style.FILL_AND_STROKE:描边和填充
注意:当模式为Paint.Style.STROKE或者Paint.Style.FILL_AND_STROKE的时候,圆的实际半径为strokeWith/2+空心内圆的半径,如下图,蓝色圆到圆心的距离为圆的半径,绿色为描边的宽度。
mPaint.setStrokeWidth(4);//描边宽度
mPaint.setStrokeCap(Paint.Cap.ROUND); //设置画笔的线帽
Paint.Cap.ROUND(圆角效果);Paint.Cap.BUTT(默认效果,无效果);Paint.Cap. SQUARE(小矩形)
mPaint.setStrokeJoin(Paint.Join.MITER);//设置线段连接处样式(拐角样式)
Paint.Join.MITER(默认,拐角为尖的);Paint.Join.ROUND(拐角为弧形);
Paint.Join.BEVEL(拐角为切线)
mPaint.setShader(new SweepGradient(200, 200, Color.BLUE, Color.RED)); //设置渲染器
包括LinearGradient(线性渲染);RadialGradient(环形渲染);SweepGradient(扫描渲染)
BitmapShader(位图渲染);以及ComposeShader(组合渲染)
mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DARKEN)); //设置图层混合模式
PorterDuff.Mode.CLEAR、SRC、DST、SRC_OVER、DST_OVER、SRC_IN、DST_IN
SRC_OUT、DST_OUT、SRC_ATOP、DST_ATOP、XOR、DARKEN、LIGHTEN、MULTIPLY、SCREEN、ADD、OVERLAY模式
如下图:蓝色正方形为srcBitmap,黄色圆为dstBitmap
mPaint.setColorFilter(new LightingColorFilter(0x00ffff, 0x000000)); //设置颜色过滤器
mPaint.setFilterBitmap(true); //设置双线性过滤,使图片颜色过渡更平滑,避免出现马赛克效果
mPaint.setMaskFilter(new BlurMaskFilter(10, BlurMaskFilter.Blur.NORMAL));//设置画笔遮罩滤镜 ,传入度数和样式
mPaint.setTextScaleX(2);// 设置文本缩放倍数
mPaint.setTextSize(38);// 设置字体大小
mPaint.setTextAlign(Paint.Align.LEFT);//对其方式
mPaint.setUnderlineText(true);// 设置下划线
String str = “Hello World!”;
Rect rect = new Rect();
mPaint.getTextBounds(str, 0, str.length(), rect); //测量文本大小,将文本大小信息存放在rect中
mPaint.measureText(str); //获取文本的宽
FontMetrics fontMe = mPaint.getFontMetrics(); //获取字体度量对象
FontMetrics中包括以下几个属性
public static class FontMetrics {
/**
* The maximum distance above the baseline for the tallest glyph in
* the font at a given text size.
*/
public float top;
/**
* The recommended distance above the baseline for singled spaced text.
*/
public float ascent;
/**
* The recommended distance below the baseline for singled spaced text.
*/
public float descent;
/**
* The maximum distance below the baseline for the lowest glyph in
* the font at a given text size.
*/
public float bottom;
/**
* The recommended additional space to add between lines of text.
*/
public float leading;
}