Android自定义View之绘制虚线

开发中遇到需要画虚线,我们首先就会想到ShapeDrawable,在布局中加一个View,并给它添加一个虚线背景,是挺简单的。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">
    <size android:height="1dp" />
    <stroke
        android:dashGap="4dp"
        android:dashWidth="8dp"
        android:width="1dp"
        android:color="#ffeaebf0" />
</shape>
<View
       android:layout_width="match_parent"
       android:layout_height="2dp"
       android:layout_gravity="center_vertical"
       android:layerType="software"
       android:background="@drawable/shape_dash_line" />

添加虚线背景,好理解,可是android:layerType="software"是干什么的?这是因为我们现在的手机默认都是开启了硬件加速的,而dashGap不支持硬件加速,我们需要把硬件加速关了就好了。使用ShapeDrawable实现虚线的方式虽然简单,但是简单就意味着不灵活。比如说要求虚线是根据用户操作来判断要不要添加的,要实现动态改变虚线的粗细和颜色等样式呢,不可能一个颜色写一个ShapeDrawable吧,这种情况下就不如使用Canvas来实现方便了。

我们都知道Canvas只有drawLine方法,没有画虚线的方法,但是我们可以用画笔Paint的setPathEffect(PathEffect effect)方法,PathEffect一共有五个子类:ComposePathEffect, CornerPathEffect, DashPathEffect, DiscretePathEffect, PathDashPathEffect, SumPathEffect, 其中的DashPathEffect就是可以用来实现虚线效果的,但是通过查阅资料发现它有一个弊端:不支持硬件加速!好吧,那我们用drawPath来绘制路径吧。

public class DashLineView extends View {

    private Paint mPaint;
    private Path mPath;
    //虚线颜色
    private int backgroundColor;
    //虚线粗细
    private int strokeWidth;
    //虚线宽度
    private int dashWidth;
    //虚线隔断宽度
    private int dashSpaceWidth;

    public DashLineView(Context context) {
        super(context);
        initView();
    }

    public DashLineView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        obtainAttributes(context, attrs);
        initView();
    }

    public DashLineView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        obtainAttributes(context, attrs);
        initView();
    }

    private void obtainAttributes(Context context, AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.DashLineView);
        backgroundColor = ta.getColor(R.styleable.DashLineView_pt_backgroundColor, getResources().getColor(R.color.line));
        strokeWidth = ta.getInt(R.styleable.DashLineView_pt_strokeWidth, ScreenUtil.dip2px(context, 1));
        dashWidth = ta.getInt(R.styleable.DashLineView_pt_dashWidth, ScreenUtil.dip2px(context, 4));
        dashSpaceWidth = ta.getInt(R.styleable.DashLineView_pt_dashSpaceWidth, ScreenUtil.dip2px(context, 3));
        ta.recycle();
    }

    private void initView(){
        //使用isInEditMode解决可视化编辑器无法识别自定义控件的问题
        if (isInEditMode()) {
            return;
        }

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        // 需要加上这句,否则画不出东西
        mPaint.setStyle(Paint.Style.STROKE);
        mPath = new Path();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //自定义的View能够使用wrap_content或者是match_parent的属性
        setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight());
    }

    @Override
    protected void onDraw(Canvas canvas) {

        mPaint.setColor(backgroundColor);
        mPaint.setStrokeWidth(strokeWidth);
        mPaint.setPathEffect(new DashPathEffect(new float[] { dashWidth, dashSpaceWidth }, 0));

        int centerY = getHeight() / 2;
        mPath.reset();
        mPath.moveTo(0, centerY);
        mPath.lineTo(getWidth(), centerY);
        canvas.drawPath(mPath, mPaint);
    }

    public void setDashLineColor(int bgColor) {
        this.backgroundColor = getResources().getColor(bgColor);
    }

}

我这里只提供了setDashLineColor方法动态设置虚线的颜色,大家可以根据需求自行添加方法。

/**
     * 虚线颜色
     * @param color
     */
    public void setLineViewColor(int color){
        mDashLineView.setDashLineColor(color);
    }

attr.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="DashLineView">
        <attr name="pt_backgroundColor" format="color"/>
        <attr name="pt_strokeWidth" format="dimension"/>
        <attr name="pt_dashWidth" format="dimension"/>
        <attr name="pt_dashSpaceWidth" format="dimension"/>
    </declare-styleable>
</resources>

ScreenUtil.java

public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

原理上还真的是比较简单的,公司项目用到,以作记录之用。以下是实现出的效果图


1.png
2.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。