Android简易仪表盘

效果截图:

 

代码:

Paint paint = new Paint();
float sensor = 0;
int max = 0;

public YB_View(Context context) {
    super(context);
}

public YB_View(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    paint.setAntiAlias(true);
    paint.setStyle(Paint.Style.STROKE);
    paint.setTextSize(20);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    float mx = getWidth() / 2 - 1;
    float my = getHeight() / 2 - 1;
    max = 100;

    //绘制中心圆
    paint.setColor(Color.RED);
    paint.setStyle(Paint.Style.FILL);
    canvas.drawCircle(mx, my, 10, paint);
    paint.setStyle(Paint.Style.STROKE);
    //绘制指针
    paint.setStrokeWidth(5);
    canvas.save();
    canvas.rotate(-135 + sensor / max * 270, mx, my);
    canvas.drawLine(mx, my, mx, 20, paint);
    canvas.restore();

    //绘制刻度
    paint.setStrokeWidth(1);
    paint.setColor(Color.BLACK);
    for (int i = 0; i < 101; i++) {
        canvas.save();
        canvas.rotate((float) (-135 + i * 2.7), mx, my);
        if (i % 10 == 0) {
            canvas.drawText(i * (max / 100) + "", mx - 10, 40, paint);
            canvas.drawLine(mx, 1, mx, 25, paint);
        }
        canvas.drawLine(mx, 1, mx, 15, paint);
        canvas.restore();
    }
}

 

posted @   花椒果  阅读(260)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示