Подтвердить что ты не робот

Создание горизонтальных и вертикальных пунктирных линий в android

Я хочу рисовать горизонтальные и вертикальные пунктирные линии в андроиде, используя фигуры.

Я хочу рисовать вот так

enter image description here

Для горизонтальной линии

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line" >

    <stroke
        android:dashGap="6px"
        android:dashWidth="6px"
        android:color="#C7B299" />

</shape>

Для вертикальной линии

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line" >
<size
     android:height="400dp"/>
    <stroke
        android:dashGap="6px"
        android:dashWidth="6px"
        android:color="#C7B299" />

</shape>

Но вертикальная пунктирная линия, не отображающая мой вывод, выглядит так:

enter image description here

Как нарисовать вертикальную линию.

4b9b3361

Ответ 1

Я нашел решение

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="90"
    android:toDegrees="90" >

    <shape android:shape="line" >
        <stroke
            android:dashGap="6px"
            android:dashWidth="6px"
            android:color="#C7B299" />
    </shape>

</rotate>

ИЛИ

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="90"
    android:toDegrees="90"
    android:drawable="@drawable/horizontal_line"/>

Ответ 2

Я думаю, что я нашел "более чистое" решение для этой проблемы, создав пользовательский вид, содержащий конкретный код для рисования пунктирных линий (как в вертикальной, так и в горизонтальной ориентации), и множество атрибутов, чтобы сделать его очень легким используйте его из макетов XML. Основное преимущество этого подхода по методу "повернутой линии" заключается в том, что вы можете установить размер пунктирной линии так, как вы обычно делаете, не беспокоясь о том, как будет выглядеть представление после вращения (после вращение применяется ко всему изображению пунктирной линии, а не только к линии, нарисованной).

Итак, вот пошаговое решение:

  • Создайте файл "/res/values/attrs.xml" со ​​следующим содержимым:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
    <declare-styleable name="DividerView">
        <attr name="color" format="color" />
        <attr name="dashLength" format="dimension" />
        <attr name="dashGap" format="dimension" />
        <attr name="dashThickness" format="dimension" />
        <attr name="orientation" format="enum">
            <enum name="horizontal" value="0" />
            <enum name="vertical" value="1" />
        </attr>
    </declare-styleable>
    
    </resources>
    

Это создает атрибуты для управления настраиваемым представлением. Примечание. Если файл выше уже существует в вашем проекте, просто скопируйте/вставьте блок "declare-stylable" внутри существующего блока "resources".

  1. Создайте класс DividerView и вставьте содержимое ниже:

    public class DividerView extends View {
    static public int ORIENTATION_HORIZONTAL = 0;
    static public int ORIENTATION_VERTICAL = 1;
    private Paint mPaint;
    private int orientation;
    
    public DividerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        int dashGap, dashLength, dashThickness;
        int color;
    
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.DividerView, 0, 0);
    
        try {
            dashGap = a.getDimensionPixelSize(R.styleable.DividerView_dashGap, 5);
            dashLength = a.getDimensionPixelSize(R.styleable.DividerView_dashLength, 5);
            dashThickness = a.getDimensionPixelSize(R.styleable.DividerView_dashThickness, 3);
            color = a.getColor(R.styleable.DividerView_color, 0xff000000);
            orientation = a.getInt(R.styleable.DividerView_orientation, ORIENTATION_HORIZONTAL);
        } finally {
            a.recycle();
        }
    
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(color);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(dashThickness);
        mPaint.setPathEffect(new DashPathEffect(new float[] { dashLength, dashGap, }, 0));
    }
    
    public DividerView(Context context) {
        this(context, null);
    }
    
    @Override
    protected void onDraw(Canvas canvas) {
        if (orientation == ORIENTATION_HORIZONTAL) {
            float center = getHeight() * .5f; 
            canvas.drawLine(0, center, getWidth(), center, mPaint);
        } else {
            float center = getWidth() * .5f; 
            canvas.drawLine(center, 0, center, getHeight(), mPaint);
        }
    }
    }
    
  2. Чтобы использовать автоматическое заполнение атрибутов в файлах макета, добавьте следующее имя определение пространства в самом верхнем контейнере:

    xmlns:custom="http://schemas.android.com/apk/res/com.example"
    

Замените com.example именем вашего пакета. Вы также можете изменить custom на любой префикс, который лучше соответствует вашим потребностям. Примечание. Возможно, вам придется перезапустить Eclipse, чтобы автоматически завершить работу после изменений в файле attrs.xml.

  1. И, наконец, создайте свои пунктирные линии, вставив следующие элемент на вашем макете, как и любой другой вид:

    <com.example.DividerView
        android:layout_width="1dp"
        android:layout_height="fill_parent"
        android:layerType="software" 
        custom:color="@color/grey"
        custom:orientation="vertical"
        custom:dashLength="1dp"
        custom:dashGap="1dp"
        custom:dashThickness="1dp" />
    

Надеюсь, это поможет!

Ответ 3

Если View имеет ширину 1dp, то просто поворачивать горизонтальную линию недостаточно. Длина вертикальных линий будет 1dp, поскольку она сначала будет выведена горизонтально, а затем повернута. Вот трюк для решения этой проблемы:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:left="-300dp"
        android:right="-300dp">
        <rotate
            android:drawable="@drawable/dash_line_divider_horizontal"
            android:fromDegrees="90"
            android:toDegrees="90"/>
    </item>
</layer-list>

Ответ 4

Это работает для меня:

vertical_line.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="@android:color/transparent"/>
    <stroke
        android:width="1px"
        android:color="#60000000"
        android:dashGap="5px"
        android:dashWidth="5px" />
</shape>

В макете:

<View
        android:layout_width="1dp"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:background="@drawable/vertical_line" />

Ответ 5

Это хорошо решает проблему. Создайте line_dash.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:bottom="-1dp"
        android:left="-1dp"
        android:right="-1dp"
        android:top="0dp">

        <shape android:shape="rectangle">
            <stroke
                android:width="1dp"
                android:color="@color/grey_20"
                android:dashGap="3dp"
                android:dashWidth="3dp" />

            <solid android:color="@android:color/transparent" />

            <padding
                android:bottom="10dp"
                android:left="10dp"
                android:right="10dp"
                android:top="10dp" />
        </shape>
    </item>
</layer-list>

Используйте это так

 <View
       android:layout_width="match_parent"
       android:layout_height="1dp"
       android:layout_margin="@dimen/spacing_middle"
       android:background="@drawable/line_dash" />

Ответ 6

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
        android:fromDegrees="90"
        android:toDegrees="90">
    <shape android:shape="line">
        <stroke
                android:color="@color/darkGray"
                android:width="1dp"
                android:dashGap="4dp"
                android:dashWidth="2dp"/>
    </shape>
</rotate>

<View
                android:layerType="software"
                android:background="@drawable/bg_vertical_dash_gray_1dp"
                android:layout_width="@dimen/_15sdp"
                android:layout_height="@dimen/_30sdp"/>

Ключом к приведенному выше коду для работы является использование android:layerType="software". Для получения дополнительной информации, проверьте эту ссылку.

Ответ 7

Это решение работает на 100% и желает помочь вам:

Сначала создайте чертеж, который будет рисовать горизонтальную пунктирную линию.

Let dashed line drawable name is horizontal_dashed_line.xml

  <?xml version="1.0" encoding="utf-8"?>
  <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line">

     <stroke
      android:width="3dp"
      android:color="#80ffffff"
      android:dashWidth="20dp"
      android:dashGap="5dp" />
  </shape>

если вы хотите иметь вертикальную пунктирную линию, вы должны повернуть этот чертеж следующим образом:

Let drawable name is vertical_dashed_line.xml

  <?xml version="1.0" encoding="utf-8"?>
  <rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="90"
    android:toDegrees="90"
    android:pivotX="50%"
    android:pivotY="50%"
    android:drawable="@drawable/horizontal_dashed_line">

  </rotate>

Теперь у вас есть горизонтальная и вертикальная пунктирная линия.

Как использовать:

Чтобы нарисовать горизонтальную линию, просто добавьте horizontal_dashed_line.xml в свой макет.  Например:

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/horizontal_dashed_line"

    </RelativeLayout>

Но если вы хотите вертикальную линию, просто добавьте vertical_dashed_line.xml вместо horizontal_dashed_line.xml. Например:

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/vertical_dashed_line"

    </RelativeLayout>

Удачи!

Ответ 8

Для вертикальной линии:

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="90"
    android:toDegrees="90">
    <shape
        android:shape="line">
        <stroke
            android:width="2dp"
            android:color="#ff00ff"
            android:dashWidth="8dp"
            android:dashGap="5dp" />
        <size android:width="120dp" />
    </shape>
</rotate>

Для горизонтальной линии:

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android">
    <shape
        android:shape="line">
        <stroke
            android:width="2dp"
            android:color="@color/accent_color"
            android:dashWidth="3dp"
            android:dashGap="2dp" />
    </shape>
</rotate>