Android绘制虚线

Android绘制虚线的两种方式

1.自定义view

看到网上很多人说用drawLine绘制,但是其实根本就没有效果,真正效果的是drawPath这个方法,话不多说直接上代码

public class DotView extends View {

    private Paint mLinePaint;
    private Paint mPaint;
    private Path mPath;
    private Context context;
    public DotView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStrokeWidth(dip2px(context,0.5f));
        mPaint.setColor(getResources().getColor(R.color.colorPrimary));
        mPaint.setStyle(Paint.Style.STROKE);
        DashPathEffect dashPathEffect1 = new DashPathEffect(new float[]{dip2px(context,3), dip2px(context,3)}, 0);
        mPaint.setPathEffect(dashPathEffect1);

        mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mLinePaint.setStrokeWidth(1);
        mLinePaint.setStyle(Paint.Style.STROKE);
        mLinePaint.setColor(getResources().getColor(R.color.colorAccent));

        mPath = new Path();
        this.context = context;
    }
    public DotView(Context context) {
        this(context, null);
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPath.reset();
        mPath.moveTo(100, 100);
        mPath.lineTo(100, 200);
        canvas.drawPath(mPath, mPaint);
    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }
}
注解:DashPathEffect参数含义new float[]{dip2px(context,3), dip2px(context,4)} :3:代表实现长度 4:代表两个实现间距离  最后面的0:代表开始的偏移量

2.使用shape
dashWidth:虚线宽度,0表示实线 ;dashGap:虚线间隔
<?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="6dp"
        android:dashWidth="9dp"
        android:width="6dp"
        android:color="#848C99" />
</shape>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值