由于工作需要,最近在研究一个类似QQ消息划掉的效果
(很多强迫症患者童鞋对这个简直是爱不释手,当然这个也包括我自己)。
这个效果的核心其实就是贝塞尔曲线,下面附上百度出来的贝塞尔曲线的原理:
贝塞尔曲线就是这样的一条曲线,它是依据四个位置任意的点坐标绘制出的一条光滑曲线。
在历史上,研究贝塞尔曲线的人最初是按照已知曲线参数方程来确定四个点的思路设计出这种矢量曲线绘制法。
贝塞尔曲线的有趣之处更在于它的“皮筋效应”,也就是说,随着点有规律地移动,
曲线将产生皮筋伸引一样的变换,带来视觉上的冲击。1962年,
法国数学家Pierre Bézier第一个研究了这种矢量绘制曲线的方法,并给出了详细的计算公式,
因此按照这样的公式绘制出来的曲线就用他的姓氏来命名是为贝塞尔曲线。
附上安卓代码:
private void drawBezier(Canvas canvas) {
mPaint.setStyle(Paint.Style.STROKE);
Point[] points = calculate(new Point(mBaseX, mBaseY), new Point(mTargetX + mDest.getWidth() / 2f, mTargetY + mDest.getHeight() / 2f));
float centerX = (points[0].x + points[1].x + points[2].x + points[3].x) / 4f;
float centerY = (points[0].y + points[1].y + points[2].y + points[3].y) / 4f;
Path path1 = new Path();
path1.moveTo(points[0].x, points[0].y);
path1.quadTo((points[2].x + points[3].x) / 2, (points[2].y + points[3].y) / 2, points[1].x, points[1].y);
canvas.drawPath(path1, mPaint);
Path path2 = new Path();
path2.moveTo(points[2].x, points[2].y);
path2.quadTo((points[0].x + points[1].x) / 2, (points[0].y + points[1].y) / 2, points[3].x, points[3].y);
canvas.drawPath(path2, mPaint);
}
/**
* ax=by=0 x^2+y^2=s/2
*
* ==>
*
* x=a^2/(a^2+b^2)*s/2
*
* @param start
* @param end
* @return
*/
private Point[] calculate(Point start, Point end) {
float a = end.x - start.x;
float b = end.y - start.y;
float x = (float) Math.sqrt(a * a / (a * a + b * b) * (mStrokeWidth / 2f) * (mStrokeWidth / 2f));
float y = -b / a * x;
System.out.println("x:" + x + " y:" + y);
Point[] result = new Point[4];
result[0] = new Point(start.x + x, start.y + y);
result[1] = new Point(end.x + x, end.y + y);
result[2] = new Point(start.x - x, start.y - y);
result[3] = new Point(end.x - x, end.y - y);
return result;
}