https://blog.csdn.net/YX_BB/article/details/104561359
在上篇文章中,我们实现了圆形图片圆角图片,基本上已经满足了日常开发中的需要。那如果想要更多的图形效果该怎么办呢?与我们在现实中的绘图方式一致,用笔(Paint)在纸(Canvas)上按照一定的路径(Path),即可形成特定的图画。一个图形的Path是固定,所以,我们可以通过改变Paint和Canvas来实现想要的效果。如下
这里以心形图片为例,展示几种不同的实现方法,首先先实现心形图片的Path。
公式:t 表示点(x,y)在坐标系中的角度
x = 16 sin^3 t
y = 13 cos t - 5 cos 2t - 2 cos 3t - cos 4t
/**
* 心形曲线
*/
private Path getHeartPath() {
int n = 100;
// 计算缩放比例
float scale = getWidth() / 17f / 2f;
// 将360度平均分为 100份,每个弧度对应一个点
float interval = (float) (2 * Math.PI / 100);
// 定义初始弧度degree
float degree = 0;
Point[] points = new Point[n];
for (int i = 0; i < n; i++) {
// 根据心形曲线公式,计算出每个弧度对应的点的坐标
// 当degree = 90度的时候,x取最大值16。当degree = 180度的时候,y取最小值 -17。
// 即保证y * scale * 17 * 2 = height的时候,曲线的与控件相切,以此计算出scale的值
float x = (float) ((16 * Math.pow(Math.sin(degree), 3)) * scale);
float y = (float) ((13 * Math.cos(degree) - 5 * Math.cos(2 * degree) - 2 * Math.cos(3 * degree) - Math.cos(4 * degree)) * scale);
points[i] = new Point(x + getWidth() / 2f, -y + getHeight() / 2f);
degree = degree + interval;
}
// 连线
Path path = new Path();
path.moveTo(points[0].x, points[0].y);
for (int i = 1; i < n; i++) {
path.lineTo(points[i].x, points[i].y);
}