Android开发之自定义控件——直尺

来源:互联网 发布:superslide.min.js 编辑:程序博客网 时间:2024/06/05 08:23

Android开发之自定义控件——直尺

本人的第一篇技术博客,希望能够在分享的路上走的更远。
先上效果图:
这里写图片描述
涉及到的知识点:
- Paint类
- Cancas类
- Path类

* 由于功能简单,此处不做详细讲解。直接贴出代码。后续会继续更新相关内容。*

代码块

public class RulerView extends View {    private Paint paint;    private int count = 10;    private int length = count * 10;    private Paint textPaint;    public RulerView(Context context) {        super(context);    }    public RulerView(Context context, AttributeSet attrs) {        super(context, attrs);        paint = new Paint();        paint.setStyle(Paint.Style.STROKE);        paint.setStrokeJoin(Paint.Join.ROUND);        paint.setStrokeWidth(1);        paint.setColor(Color.GRAY);        textPaint = new Paint();        textPaint.setStyle(Paint.Style.FILL);        textPaint.setTextSize(30);        textPaint.setColor(Color.GRAY);    }    public RulerView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        Paint.FontMetrics fontMetrics = textPaint.getFontMetrics();        //计算文字的高度        float fontHeight = fontMetrics.descent - fontMetrics.ascent;        int width = getMeasuredWidth();        int height = getMeasuredHeight();        BigDecimal bigDecimal = new BigDecimal(width - 2);        //刻度区域距尺子两边的距离        float margin = (float) bigDecimal.multiply(new BigDecimal(0.1)).divide(new BigDecimal(2)).doubleValue();        canvas.drawRect(1, 2, width - 1, height - 2, paint);        BigDecimal mm = bigDecimal.multiply(new BigDecimal(0.9)).divide(new BigDecimal(length));        Path path = new Path();        for (int i = 0; i <= length; i++) {            float x = (float) (margin + mm.multiply(new BigDecimal(i)).doubleValue());            path.moveTo(x, height - 2);            x = (float) (margin + mm.multiply(new BigDecimal(i)).doubleValue());            if (i == 0 || i % 10 == 0) {                path.lineTo(x, (float) ((height) * 0.4));                String units = i / 10 + "";                if (i == 0) {                    units += "cm";                    //0刻度的时候,0应该在刻度的正上方                    canvas.drawText(units, x - textPaint.measureText("0") / 2, (float) ((height) * 0.4) - fontHeight / 4, textPaint);                } else {                    float textWidth = textPaint.measureText(units);                    canvas.drawText(units, x - textWidth / 2, (float) ((height) * 0.4) - fontHeight / 4, textPaint);                }            } else if (i % 5 == 0) {                path.lineTo(x, (float) ((height) * 0.5));            } else {                path.lineTo(x, (float) ((height) * 0.7));            }        }        canvas.drawPath(path, paint);    }}
0 0