public class GradualView extends View {
private Context context;
private Paint paint;//画笔
private Paint paintFull;//实心圆画笔
private Paint textPaint;//标识字画笔
private Paint valuePaint;//移动小球画笔
private int[] mColors;//渐变色数组
private int centerX;//中心X
private int centerY;//中心Y
private int srcH;//控件高度
private float startAngle = 270;//圆弧起始角度
private float sweepAngle = 90;//圆弧所占度数
private float airValue = 66;
/**
* 直接在代码中调用时,使用该函数
*/
public GradualView(Context context) {
super(context);
initData(context);
}
/**
* 在xml中使用自定义view时,使用这个函数
*/
public GradualView(Context context, AttributeSet attrs) {
super(context, attrs);
initData(context);
}
/**
* 可以由上一个函数中手动调用
* @param defStyle 自定义函数中的attrs表示view的属性集,defStyle表示默认的属性资源集的id
*/
public GradualView(Context context, AttributeSet atrrs, int defStyle) {
super(context, atrrs, defStyle);
}
/**
* 初始化
*/
private void initData(Context context) {
this.context = context;
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
//颜色的跨度跟颜色的个数有关,均跨度=360/颜色个数,角度按顺时针,从0-360
mColors = new int[]{
0xFF660099,//紫色0
0xFF330033,//褐色
0xFFFF6600,//橘色
0xFFFFFF00,//黄色
0xFF99FF00,//草绿色
0xFFFF0000,//红色
0xFF660099,//紫色360
};
Shader s = new SweepGradient(0, 0, mColors, null);
paint.setAntiAlias(true);//设置画笔为无锯齿
paint.setStrokeWidth(dip2px(context, 14));//线宽
paint.setShader(s);
paintFull = new Paint(Paint.ANTI_ALIAS_FLAG);
paintFull.setStyle(Paint.Style.FILL_AND_STROKE);
paintFull.setAntiAlias(true);//设置画笔为无锯齿
paintFull.setShader(s);
textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setTextSize(dip2px(context, 22));//设置字体大小
textPaint.setColor(0xFFFFFFFF);
valuePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
valuePaint.setAntiAlias(true);//设置画笔为无锯齿
}
public void setAirValue(float airValue) {
this.airValue = airValue;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
srcH = h;
centerX = w / 2;
centerY = h / 2;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float r = srcH / 2 - paint.getStrokeWidth() * 0.5f - dip2px(context, 200);
//移动中心
canvas.translate(centerX, centerY);
RectF oval = new RectF();
oval.left = -r;//左边
oval.top = -r;//上边
oval.right = r;//右边
oval.bottom = r;//下边
canvas.drawArc(oval, startAngle, sweepAngle, false, paint); //绘制圆弧
}
/**
* dip转px
*/
private int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
}
画弧
最新推荐文章于 2024-03-02 12:27:00 发布