前言
纸上得来终觉浅,绝知此事要躬行。
直接上代码
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
public class SpiderView extends View{
private Paint radarPaint,valuePaint;
private float radius;
private int centerX;
private int centerY;
private int count = 6;
private int maxValue = 6;
double[] data = {2,5,1,6,4,5};
private int a = 360/6;
public SpiderView(Context context) {
super(context);
init();
}
public SpiderView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public SpiderView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
radarPaint = new Paint();
radarPaint.setStyle(Paint.Style.STROKE);
radarPaint.setColor(Color.GREEN);
valuePaint = new Paint();
valuePaint.setStyle(Paint.Style.FILL);
valuePaint.setColor(Color.BLUE);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
radius = Math.min(w,h)/2*0.9f;
centerX = w/2;
centerY = h/2;
postInvalidate();
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawPolygon(canvas);
drawLine(canvas);
drawRegion(canvas);
}
//画数据区域
private void drawRegion(Canvas canvas) {
Path path = new Path();
valuePaint.setAlpha(127);
for(int i=0;i<count;i++){
double percent = data[i]/maxValue;
float x = (float)(centerX + radius * percent * Math.cos(Math.toRadians(a)*i));
float y = (float)(centerY + radius * percent * Math.sin(Math.toRadians(a)*i));
if(i==0){
path.moveTo(x,y);
}else{
path.lineTo(x,y);
}
canvas.drawCircle(x,y,10,valuePaint);
}
valuePaint.setStyle(Paint.Style.FILL_AND_STROKE);
canvas.drawPath(path,valuePaint);
}
//画角线
private void drawLine(Canvas canvas) {
Path path = new Path();
for(int i=0;i<count;i++){
path.reset();
path.moveTo(centerX,centerY);
float x = (float)(centerX + radius * Math.cos(Math.toRadians(a)*i));
float y = (float)(centerY + radius * Math.sin(Math.toRadians(a)*i));
path.lineTo(x,y);
canvas.drawPath(path,radarPaint);
}
}
//画网格框
private void drawPolygon(Canvas canvas) {
Path path = new Path();
float r = radius/count;
for(int i=1;i<=count;i++){
float curR = r * i;
path.reset();
for(int j=0;j<count;j++){
if(j==0){
path.moveTo(centerX + curR, centerY);
}else{
float x = (float)(centerX + curR * Math.cos(Math.toRadians(a)*j));
float y = (float)(centerY + curR*Math.sin(Math.toRadians(a)*j));
path.lineTo(x,y);
}
}
// path.close();
canvas.drawPath(path,radarPaint);
}
}
}
效果图如下:
缺了一个口.jpg
- 本来就没有完美的事情,索性就让它缺一个口吧,代码中注释的那句就是解决的方案。
遇到的问题
- 三角函数的问题,里面一定要用弧度弧度弧度,Math.cos(Math.toRadians(a)i)和Math.sin(Math.toRadians(a)i),关于弧度还是角度看这里
网友评论