自定义控件之实现仪表盘 搬运自 rengwuxian

     凉风起天末,君子意如何.闲来无事,开始做一下自定义控件的学习.手写一个仪表盘.效果是下面酱紫的.

自定义控件之实现仪表盘 搬运自 rengwuxian_第1张图片

下面上一下代码: 

 

**
 * Created by lz on 2018/10/24.
 * 功能描述:仪表盘
 */

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class DashBoard extends View {
    private static final int ANGLE = 120;
    private static final float RADIUS = Utils.dp2px(150);
    private static final float LENGTH = Utils.dp2px(100);
    PathDashPathEffect mPathDashPathEffect;
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Path path = new Path();

    public DashBoard(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    {
        paint.setStyle(Paint.Style.STROKE);
        //paint.setColor(getResources().getColor(R.color.colorPrimary));
        paint.setStrokeWidth(Utils.dp2px(2));
        path.addRect(0, 0, Utils.dp2px(2), Utils.dp2px(10), Path.Direction.CW);
        Path arc = new Path();
        arc.addArc(getWidth() / 2 - RADIUS, getHeight() / 2 - RADIUS,
            getWidth() / 2 + RADIUS, getHeight() / 2 + RADIUS,
            90 + ANGLE / 2, 360 - ANGLE);
        PathMeasure pathMeasure = new PathMeasure(arc,false);
        mPathDashPathEffect = new PathDashPathEffect(path, (pathMeasure.getLength()-Utils.dp2px(2)) / 20, 0, PathDashPathEffect.Style.ROTATE);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //画线
        canvas.drawArc(getWidth() / 2 - RADIUS, getHeight() / 2 - RADIUS,
            getWidth() / 2 + RADIUS, getHeight() / 2 + RADIUS,
            90 + ANGLE / 2, 360 - ANGLE, false, paint);
        //画刻度
        paint.setPathEffect(mPathDashPathEffect);
        canvas.drawArc(getWidth() / 2 - RADIUS, getHeight() / 2 - RADIUS,
            getWidth() / 2 + RADIUS, getHeight() / 2 + RADIUS,
            90 + ANGLE / 2, 360 - ANGLE, false, paint);
        paint.setPathEffect(null);
        //画指针
        canvas.drawLine(getWidth()/2,getHeight()/2,
            getWidth()/2+(float) Math.cos(Math.toRadians(getAngleFromMark(5)))*LENGTH,
            getHeight()/2+(float) Math.sin(Math.toRadians(getAngleFromMark(5)))*LENGTH,paint);
    }
    int getAngleFromMark(int mark){
        return (int)(90+(float)ANGLE/2+(360-(float)ANGLE)/20*mark);

    }
} 
public class Utils {
    //dp转px
    public static float dp2px(float dp){
       return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dp,
            Resources.getSystem().getDisplayMetrics());
    }
}

 

你可能感兴趣的:(自定义控件)