绘制文本drawText
计算文本的宽度、高度
1
2
3float textWidth = paint.measureText(text);
Paint.FontMetrics fontMetrics = paint.getFontMetrics();
float textHeight = fontMetrics.top - fontMetrics.bottom;绘制文本,文本绘制起始点在文本矩形的左下角,注意起始点(floatX, floatY)
canvas.drawText(text, floatX, floatY, paint);利用path绘制倾斜文本
1
2
3
4Path path = new Path();
path.moveTo(floatX, floatY);//移到起始点
path.lineTo(endX, endY);// 描路径
canvas.drawTextOnPath(text, path, 0, 0, paint);
绘制圆角矩形
直接绘制
drawRoundRect1
2
3RectF rect = new RectF(left, top, right, bottom);
paint.setStyle(Paint.Style.FILL);
canvas.drawRoundRect(rect, floatRX, floatRY, paint);通过裁剪路径
clipPath得到,但画布可绘制范围只剩该矩形区域1
2
3
4
5
6float r = 3;
float[] radiusArray = {r,r, r,r, r,r, r,r};//对应左、上、右、下四个角的圆角半径
Path path = new Path();
RectF rect = new RectF(left, right, top, bottom);
path.addRoundRect(rect, radiusArray, Path.Direction.CW);
canvas.clipPath(path);
绘制圆弧drawArc
默认按顺时针方向绘制,设置圆弧所在区域矩形、起始的角度、扫过的角度
1
2
3
4RectF rect = new RectF(left, top, right, bottom);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeCap(Paint.Cap.ROUND);// 设置描边线为圆角类型
canvas.drawArc(rect, startAngle, sweepAngle, false, paint);设置圆弧渐变色
1
2
3
4
5
6
7// 位置数组与色值数组对应
int[] GRADIENT_COLORS = new int[]{Color.parseColor("#F257B0"), Color.parseColor("#688FFD")};
// 取值范围0-1,0和1为3点钟位置,0.25为6点钟位置,0.5为9点钟位置,0.75为12点位置
float[] GRADIENT_POSITION = new float[]{0.45f, 1.0f};
SweepGradient gradient = new SweepGradient(cx, cy, GRADIENT_COLORS, GRADIENT_POSITION);
paint.setShader(gradient);
canvas.drawArc(rect, startAngle, sweepAngle, false, paint);
其它
androd屏幕坐标参考系,水平右方向为x轴正方向,水平左方向为x轴负方向,竖直下方向为y轴正方向,竖直上方向为y轴负方向;
画布
canvas基本操作1
2canvas.translate(dx, dy); // 移动画布中心
canvas.rotate(degree); // 画布旋转角度degree
绘制时使用屏幕的实际尺寸,不能直接使用
3px;int width = context.getResources().getDimensionPixelSize(R.dimen.dp_3px);Math类的常用运算
1
2
3
4
5
6
7
8
9
10
11
12Math.toRadians(180);//角度转弧度
Math.toDegrees(pi);//弧度转角度
Math.sin(radians);//计算三角函数sin值,传入弧度
Math.ceil(12.7);//得13 取天花板值
Math.floor(12.7);//得12 取地板值
Math.sqrt(4);// 求开方
Math.pow(x,y);//求x的y次方
Math.round(x);//求整,四舍五入
Math.min(x,y); //最小值
Math.max(x,y); //最大值
Math.abs(x);//绝对值
Math.random();// 返回0-1随机数浮点数保持精度计算
BigDecimal1
2BigDecimal bigDecimal = new BigDecimal("3.14159");
bigDecimal.setScale(2, BigDecimal.ROUND_DOWN);// 取小数点后2位动画动态取值
ValueAnimator1
2
3
4
5
6
7
8
9
10
11ValueAnimator animator = ValueAnimator.ofInt(startValue, endValue);
animator.setDuration(3000);// 设置动画持续时长
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator valueAnimator) {
// 在duration时长内,返回startValue-endValue区间的值,根据不同的值重绘界面,形成动态
int value = (int) valueAnimator.getAnimatedValue();
Log.d(TAG, "animator value:" + value);
}
});