Android自定义View之绘制虚线

布局

.color.dash_line.DashLineView
            android:id="@+id/dashLineView"
            android:layout_width="334dp"
            android:layout_height="1dp"
            android:layout_marginLeft="12dp"
            android:layout_marginTop="42dp"
            android:background="@drawable/dash_line"
            android:layerType="software" />

自定义DashLineView

public class DashLineView extends View {
    private Paint mPaint;
    private Path mPath;
    public DashLineView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(getResources().getColor(R.color.edit));
        // 需要加上这句,否则画不出东西
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(3);
        mPaint.setPathEffect(new DashPathEffect(new float[] {5, 5}, 0));
        mPath = new Path();
        mPath.addCircle(0, 0, 3, Path.Direction.CW);
        mPaint.setPathEffect(new PathDashPathEffect(mPath, 15, 0, PathDashPathEffect.Style.ROTATE));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        int centerY = getHeight() / 2;
        setLayerType(LAYER_TYPE_SOFTWARE, null);

        canvas.drawLine(0, centerY, getWidth(), centerY, mPaint);

    }

    }

你可能感兴趣的:(Android自定义View之绘制虚线)