学而实习之 不亦乐乎

Android 中实现虚线(二):自定义虚线控件

2024-01-06 21:03:11

一、自定义属性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="DashLineView">
        <attr name="lineColor" format="color"/>
        <attr name="gapWidth" format="dimension"/>
        <attr name="radius" format="dimension"/>
        <attr name="android:orientation" format="string"/>
    </declare-styleable>
</resources>

二、自定义 DashLineView

public class DashLineView extends View {

    private int lineColor;
    private float gapWidth;
    private float radius;
    private Paint mPaint;
    private Path mPath;

    public DashLineView(Context context) {
        this(context, null);
    }

    public DashLineView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DashLineView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.DashLineView,
                0,
                0);

        lineColor = a.getColor(R.styleable.DashLineView_lineColor, Color.BLACK);
        //gapWidth = a.getDimension(R.styleable.DashLineView_gapWidth, 20);
        //radius = a.getDimension(R.styleable.DashLineView_radius, 10);
        gapWidth = a.getDimensionPixelSize(R.styleable.DashLineView_gapWidth, 20);
        radius = a.getDimensionPixelSize(R.styleable.DashLineView_radius, 10);
        //orientation = a.getDimensionPixelOffset(R.styleable.DashLineView_android_orientation, 0);
        a.recycle();

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(lineColor);

        // 需要加上这句,否则画不出东西
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(radius * 2);//线宽

        //设置样式
        mPath = new Path();
        mPath.addCircle(0, 0, radius, Path.Direction.CW);
        mPaint.setPathEffect(new PathDashPathEffect(mPath, gapWidth * 2, 0,
                PathDashPathEffect.Style.ROTATE));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int centerY = getHeight() / 2;
        setLayerType(LAYER_TYPE_SOFTWARE, null);
        canvas.drawLine(0, centerY, getWidth() + 1, centerY, mPaint);

        // 半圆
        //canvas.drawLine(0, 0, getWidth() + 1, 0, mPaint);
    }
}

三、在布局中使用

<com.example.test.DashLineView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:lineColor="@color/colorPrimary"
    app:gapWidth="54px"
    app:radius="27px"/>