《Android自定义控件入门到精通》文章索引 ☞ https://blog.csdn.net/Jhone_csdn/article/details/118146683
《Android自定义控件入门到精通》所有源码 ☞ https://gitee.com/zengjiangwen/Code
文章目录
Paint基础知识
paint画笔,跟我们Ps中的画笔有点类似,比如Ps中的画笔工具和图案图章工具。
常用基础函数
我们先来系统的了解下Paint的一些基础的函数:
mPaint.setColor(Color.RED);//设置画笔颜色
mPaint.setTextAlign(Paint.Align.CENTER);//设置文本与基点的对其方式
mPaint.setAntiAlias(true);//设置是否抗锯齿
mPaint.setFlags(Paint.ANTI_ALIAS_FLAG);//添加画笔特性标识
mPaint.setDither(true);//设置是否防抖动
mPaint.setAlpha(100);//设置画笔的透明度0~255
mPaint.setARGB(55,100,100,100);//设置画笔颜色和透明度
mPaint.reset();//恢复画笔到默认状态
mPaint.getFontMetrics();//可以获取到ascent descent top bottom值
mPaint.ascent();//ascent值
mPaint.descent();//descent值
mPaint.setTextSize(24);//字体大小,通常会做sp适配
mPaint.setLetterSpacing(0.3f);//字间距,默认是0,Typical values for slight 0.05
mPaint.measureText("test");//获取文本的宽度
mPaint.setUnderlineText(true);//是否添加下划线
mPaint.setStrikeThruText(true);//是否添加删除线
mPaint.setHinting(Paint.HINTING_OFF);//设置画笔的Hint模式(没看出有啥效果)
mPaint.setFakeBoldText(true);//设置伪粗体,有些字体是没有粗体的,可以用伪粗体模拟粗体字的效果
mPaint.setTextScaleX(2f);//放大缩小文本
mPaint.setTextSkewX(2f);//倾斜文本,一般取值-0.25
mPaint.setTextLocale(Locale.CHINA);//指定语言
mPaint.getTextBounds("test",0,3,rect);//获取文本的边界
这些方法我们前面可能接触过一些,没啥难度,看注释应该就能很好的理解了,主要讲下下面这几个基础方法
mPaint.setStyle(Paint.Style.FILL);//描边,填充,描边和填充
mPaint.setStrokeWidth(10);//设置线宽,当Paint.Style.STROKE时有效
mPaint.setStrokeCap(Paint.Cap.ROUND);//设置线帽样式
mPaint.setShadowLayer(0, 0, 0, 0);//设置阴影效果
mPaint.clearShadowLayer();//清除阴影效果
mPaint.breakText();//测量
mPaint.setTypeface();//设置字体
mPaint.setStrokeJoin();//设置转折样式
mPaint.setMaskFilter();//设置滤镜
Paint.setStyle
设置画笔的样式,描边、填充、描边并填充
@Override
protected void onDraw(Canvas canvas) {
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(10);
mPaint.setColor(Color.RED);
canvas.drawRect(new Rect(40,20,100,60),mPaint);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(2);
mPaint.setColor(Color.GREEN);
canvas.drawRect(new Rect(40,20,100,60),mPaint);
mPaint.setStyle(Paint.Style.FILL);
canvas.drawText("Paint.Style.STROKE",160,40,mPaint);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setStrokeWidth(10);
mPaint.setColor(Color.RED);
canvas.drawRect(new Rect(40,120,100,160),mPaint);
mPaint.setStyle(Paint.Style