本文由 BarryZhang 原创,同时首发于barryzhang.com, 简书 ,非商业转载请注明作者和原文链接。
给定一个指定的正方形的区域,要求在该区域内画一个正N边形(正三角形、正方形、正五边形……)
public static void drawPolygon (RectF rect, Canvas canvas, Paint p, int n) {
// draw……
}
要用到一些三角函数的知识,于是我画了一幅灵魂画作:ghost::
分析:
360/n ,弧度计算为 2π/n 。 [X1=cos(a),Y1=sin(a)] 。 [Xn=cos(a*n),Yn=sin(a*n)] 。 [Ox=(rect.right+rect.left)/2 , Oy=(rect.top+rect.bottom)/2] 。 [Xn+Ox,Yn+Oy] 。 Path 来保存路径,最后使用 canvas.drawPath 来绘制出来。 简化的伪代码:
float a = 2π / n ; // 角度
Path path = new Path();
for( int i = 0; i < = n; i++ ){
float x = R * cos(a * i);
float y = R * sin(a * i);
if (i = 0){
path.moveTo(x,y); // 移动到第一个顶点
}else{
path.lineTo(x,y); //
}
}
drawPath(path);
Java代码最终的完整代码,可以直接拿去用:
public static void drawPolygon (RectF rect, Canvas canvas, Paint paintByLevel, int number) {
if(number < 3) {
return;
}
float r = (rect.right - rect.left) / 2;
float mX = (rect.right + rect.left) / 2;
float my = (rect.top + rect.bottom) / 2;
Path path = new Path();
for (int i = 0; i <= number; i++) {
// - 0.5 : Turn 90 ° counterclockwise
float alpha = Double.valueOf(((2f / number) * i - 0.5) * Math.PI).floatValue();
float nextX = mX + Double.valueOf(r * Math.cos(alpha)).floatValue();
float nextY = my + Double.valueOf(r * Math.sin(alpha)).floatValue();
if (i == 0) {
path.moveTo(nextX, nextY);
} else {
path.lineTo(nextX, nextY);
}
}
canvas.drawPath(path, paintByLevel);
}
这个项目里用到了这个函数,可以点进去看以及下载demo。
https://github.com/barryhappy/TContributionsView
本文链接: http://www.barryzhang.com/?p=510