Androidで点線/破線を作成するにはどうすればよいですか?


254

点線を作ろうとしています。私は今、これを実線に使用しています:

LinearLayout divider = new LinearLayout( this );
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, 2 );
divider.setLayoutParams( params );
divider.setBackgroundColor( getResources().getColor( R.color.grey ) );

私はこのようなものが必要ですが、しっかりしているのではなく点在しています。何百ものレイアウトを透過レイアウトとベタレイアウトの間で交互に作成しないようにしたいと思います。

回答:


517

Javaコードなし:

drawable / dotted.xml:

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

    <stroke
       android:color="#C7B299"
       android:dashWidth="10px"
       android:dashGap="10px"
       android:width="1dp"/>
</shape>

view.xml:

<ImageView
    android:layout_width="match_parent"
    android:layout_height="5dp"
    android:src="@drawable/dotted"
    android:layerType="software" />

21
Eclipseのグラフィカルレイアウトでギャップが表示されているのに、電話でギャップのないラインが表示される理由がわかりません。
ダンテ

73
気にしないで、私はここで解決策を見つけました:stackoverflow.com/questions/10843402/… レイヤータイプをソフトウェアに設定するだけ:android:layerType = "software"
Dante

7
の使用には既知のバグがありcanvas.drawLine()ます。ハードウェアアクセラレーションを無効にするcanvas.drawPath代わりに、代わりに使用できます。
hgoebl 2013

10
dp 代わりに使用してくださいpx
S.M_Emamian 2016

7
これがAndroid 6.0.1と4.4.4の両方で機能することを確認しました。注意すべき2つの点:1)確かにImageViewが必要です。2)android:layerType="software"ImageViewで設定する必要があります。
Jonik

206

パスエフェクトはペイントオブジェクトに設定されています

Paint fgPaintSel = new Paint();
fgPaintSel.setARGB(255, 0, 0,0);
fgPaintSel.setStyle(Style.STROKE);
fgPaintSel.setPathEffect(new DashPathEffect(new float[] {10,20}, 0));

ダッシュとギャップの比率を指定するint []配列により多くの数を指定することにより、あらゆる種類のドットパターンを作成できます。これは、シンプルで等しく破線の線です。


なぜこれが今私に役立つのですか?stackoverflow.com/questions/12401311/...
Chris.Zou

コンストラクターで新しいfloat [] {5,10,15,20}を試してください
シリコン

4
私はアンドロイド開発で少し新しいです。作成した線形レイアウトに破線のエフェクトを含むペイントオブジェクトをどのように追加しますか?
DirkJan 2013年

このコードを直接コピーして貼り付けましたが、何も起こりませんでした。機能させるために追加のコードを書く必要がありますか?
ジェイソン2015

50

XMLを使用して点線を作成します。
ドローアブルフォルダーにxmlを作成し、点線の枠を設定するアイテムにその背景を与えます。

XMLバックグラウンド「dashed_border」の作成:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape>
            <solid android:color="#ffffff" />
            <stroke
                android:dashGap="5dp"
                android:dashWidth="5dp"
                android:width="1dp"
                android:color="#0000FF" />
            <padding
                android:bottom="5dp"
                android:left="5dp"
                android:right="5dp"
                android:top="5dp" />
        </shape>
    </item>
</layer-list>

その背景をアイテムに追加します:

<Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/dashed_border"/>

コーナーの半径が必要な場合は<corners android:radius="5dp" />、形状に追加するだけです。詳細については、stackoverflow.com / a / 41940609/1000551をご覧ください
Vadim Kotov

レイヤーリストは単一のアイテムには不要だと思います。ルート要素として<shape>を使用しましたが、同じように機能します。
big_m

37

xmlを作成(view_line_dotted.xml):

<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="#ffff0017"
                    android:dashGap="3dp"
                    android:dashWidth="1dp" />

                <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:background="@drawable/view_line_dotted" />

説明して頂けますか?
スカイウォール2015

1
ありがとう、手がかりは<item android:bottom="-1dp" android:left="-1dp" android:right="-1dp" >、水平線が1 dpの太さである場合です。
CoolMind

驚くばかり。ほぼ箱から出して動作します。私が必要とした唯一の変更は、ストロークタグを変更することでした。2dp幅と4dp dashGap。
Sufian

APIが21未満のデバイスの場合android:layerType="software"、ビューに追加するか書き込みますview.setLayerType(View.LAYER_TYPE_SOFTWARE, null)stackoverflow.com/questions/10843402/…を参照)。
CoolMind

24

点線を描画したいときに私がしたことは、描画可能なdash_line.xmlを定義することです

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

そして、レイアウトで、背景をdash_lineとしてビューを定義します。android:layerType = "software"を含めることに注意してください。そうしないと機能しません。

<View
            android:layout_width="match_parent"
            android:layout_height="5dp"
            android:background="@drawable/dash_line"
            android:layerType="software" />

どうも!android:layerType="software"私が探していたものです!乾杯!
Toochka

20

水平&垂直の破線をサポートするカスタムの破線があります。以下のコード:

public class DashedLineView extends View
{
private float density;
private Paint paint;
private Path path;
private PathEffect effects;

public DashedLineView(Context context)
{
    super(context);
    init(context);
}

public DashedLineView(Context context, AttributeSet attrs)
{
    super(context, attrs);
    init(context);
}

public DashedLineView(Context context, AttributeSet attrs, int defStyle)
{
    super(context, attrs, defStyle);
    init(context);
}

private void init(Context context)
{
    density = DisplayUtil.getDisplayDensity(context);
    paint = new Paint();
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(density * 4);
    //set your own color
    paint.setColor(context.getResources().getColor(R.color.XXX));
    path = new Path();
    //array is ON and OFF distances in px (4px line then 2px space)
    effects = new DashPathEffect(new float[] { 4, 2, 4, 2 }, 0);

}

@Override
protected void onDraw(Canvas canvas)
{
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    paint.setPathEffect(effects);
    int measuredHeight = getMeasuredHeight();
    int measuredWidth = getMeasuredWidth();
    if (measuredHeight <= measuredWidth)
    {
        // horizontal
        path.moveTo(0, 0);
        path.lineTo(measuredWidth, 0);
        canvas.drawPath(path, paint);
    }
    else
    {
        // vertical
        path.moveTo(0, 0);
        path.lineTo(0, measuredHeight);
        canvas.drawPath(path, paint);
    }

}
}

このアプローチはxmlシェイプよりも望ましいですか?
IgorGanapolsky 2015

パーフェクト!私が探していたもの
ジョブM

9

このクラスを使用すると、「破線と下線」の効果を複数行のテキストに適用できます。DashPathEffectを使用するには、TextViewのhardwareAcceleratedをオフにする必要があります(DashPathEffectメソッドには長いテキストに関する問題があります)。ここで私のサンプルプロジェクトを見つけることができます:https : //github.com/jintoga/Dashed-Underlined-TextView/blob/master/Untitled.png

public class DashedUnderlineSpan implements LineBackgroundSpan, LineHeightSpan {

    private Paint paint;
    private TextView textView;
    private float offsetY;
    private float spacingExtra;

    public DashedUnderlineSpan(TextView textView, int color, float thickness, float dashPath,
                               float offsetY, float spacingExtra) {
        this.paint = new Paint();
        this.paint.setColor(color);
        this.paint.setStyle(Paint.Style.STROKE);
        this.paint.setPathEffect(new DashPathEffect(new float[] { dashPath, dashPath }, 0));
        this.paint.setStrokeWidth(thickness);
        this.textView = textView;
        this.offsetY = offsetY;
        this.spacingExtra = spacingExtra;
    }

    @Override
    public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v,
                             Paint.FontMetricsInt fm) {
        fm.ascent -= spacingExtra;
        fm.top -= spacingExtra;
        fm.descent += spacingExtra;
        fm.bottom += spacingExtra;
    }

    @Override
    public void drawBackground(Canvas canvas, Paint p, int left, int right, int top, int baseline,
                               int bottom, CharSequence text, int start, int end, int lnum) {
        int lineNum = textView.getLineCount();
        for (int i = 0; i < lineNum; i++) {
            Layout layout = textView.getLayout();
            canvas.drawLine(layout.getLineLeft(i), layout.getLineBottom(i) - spacingExtra + offsetY,
                    layout.getLineRight(i), layout.getLineBottom(i) - spacingExtra + offsetY,
                    this.paint);
        }
    }
}

結果:

破線の下線


8

垂直線を探している場合は、このドローアブルを使用してください。

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:top="-8dp"
        android:bottom="-8dp"
        android:left="-8dp">
        <shape>
            <solid android:color="@android:color/transparent"/>
            <stroke
                android:width="4dp"
                android:color="#ffffff"
                android:dashGap="4dp"
                android:dashWidth="4dp"/>
        </shape>
    </item>
</layer-list>

負の上下および左の値は、シェイプの不要な側面を削除し、単一の破線を残します。

そのようなビューで使用してください。

<View
android:layout_width="4dp"
android:layout_height="match_parent"
android:background="@drawable/dash_line_vertical"
android:layerType="software" />

4

以下をレイアウトの背景として使用しました:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
<stroke
   android:width="1dp"
    android:dashWidth="10px"
   android:dashGap="10px"
    android:color="android:@color/black" 
   />
</shape>

なぜandroid:shape="rectangle"線の代わりに?
IgorGanapolsky

4

EditTextの破線の破線を作成しました。どうぞ。新しいxmlを作成します。たとえば、ここにdashed_border.xmlコード:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:bottom="1dp"
    android:left="-2dp"
    android:right="-2dp"
    android:top="-2dp">
    <shape android:shape="rectangle">
        <stroke
            android:width="2dp"
            android:color="#000000"
            android:dashGap="3dp"
            android:dashWidth="1dp" />

        <solid android:color="#00FFFFFF" />

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

たとえば、EditTextで新しいxmlファイルを使用します。

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/dashed_border"/>

乾杯!:)



3

点線の背景が最適に機能するための最適なソリューション

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

3

キャンバス上のドット効果の場合、この属性をペイントオブジェクトに設定します。

paint.setPathEffect(new DashPathEffect(new float[] {0,30}, 0));

そして、レンダリングがあなたに合うように値30を変更します。これは、各ドット間の「距離」を表します。

ここに画像の説明を入力してください


2

私のために働いた唯一のこと、そして私がそれが最も簡単な方法だと思うのは、次のようなペイントオブジェクトでパスを使うことです:

    Paint paintDash = new Paint();
    paintDash.setARGB(255, 0, 0, 0);
    paintDash.setStyle(Paint.Style.STROKE);
    paintDash.setPathEffect(new DashPathEffect(new float[]{10f,10f}, 0));
    paintDash.setStrokeWidth(2);
    Path pathDashLine = new Path();

次に、onDraw():(ondraw呼び出しの間にこれらのポイントを変更すると、重要な呼び出しがリセットされ、Pathがすべての動きを保存します)

    pathDashLine.reset();
    pathDashLine.moveTo(porigenX, porigenY);
    pathDashLine.lineTo(cursorX,cursorY);
    c.drawPath(pathDashLine, paintDash);

2

Ruidgeのソリューションは気に入りましたが、XMLからのより詳細な制御が必要でした。そこで、それをKotlinに変更し、属性を追加しました。

1)Kotlinクラスをコピーします。

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View

class DashedDividerView : View {
constructor(context: Context) : this(context, null, 0)
constructor(context: Context, attributeSet: AttributeSet) : this(context, attributeSet, 0)

companion object {
    const val DIRECTION_VERTICAL = 0
    const val DIRECTION_HORIZONTAL = 1
}

private var dGap = 5.25f
private var dWidth = 5.25f
private var dColor = Color.parseColor("#EE0606")
private var direction = DIRECTION_HORIZONTAL
private val paint = Paint()
private val path = Path()

constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
    context,
    attrs,
    defStyleAttr
) {
    val typedArray = context.obtainStyledAttributes(
        attrs,
        R.styleable.DashedDividerView,
        defStyleAttr,
        R.style.DashedDividerDefault
    )

    dGap = typedArray.getDimension(R.styleable.DashedDividerView_dividerDashGap, dGap)
    dWidth = typedArray.getDimension(R.styleable.DashedDividerView_dividerDashWidth, dWidth)
    dColor = typedArray.getColor(R.styleable.DashedDividerView_dividerDashColor, dColor)
    direction =
        typedArray.getInt(R.styleable.DashedDividerView_dividerDirection, DIRECTION_HORIZONTAL)

    paint.color = dColor
    paint.style = Paint.Style.STROKE
    paint.pathEffect = DashPathEffect(floatArrayOf(dWidth, dGap), 0f)
    paint.strokeWidth = dWidth

    typedArray.recycle()
}

override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    path.moveTo(0f, 0f)

    if (direction == DIRECTION_HORIZONTAL) {
        path.lineTo(measuredWidth.toFloat(), 0f)
    } else {
        path.lineTo(0f, measuredHeight.toFloat())
    }
    canvas.drawPath(path, paint)
}

}

2)/ resディレクトリにattrファイルを作成し、これを追加します

 <declare-styleable name="DashedDividerView">
    <attr name="dividerDashGap" format="dimension" />
    <attr name="dividerDashWidth" format="dimension" />
    <attr name="dividerDashColor" format="reference|color" />
    <attr name="dividerDirection" format="enum">
        <enum name="vertical" value="0" />
        <enum name="horizontal" value="1" />
    </attr>
</declare-styleable>

3)スタイルファイルにスタイルを追加する

 <style name="DashedDividerDefault">
    <item name="dividerDashGap">2dp</item>
    <item name="dividerDashWidth">2dp</item>
    <!-- or any color -->
    <item name="dividerDashColor">#EE0606</item>
    <item name="dividerDirection">horizontal</item>
</style>

4)これで、デフォルトのスタイルを使用できます

<!-- here will be your path to the class -->
<com.your.package.app.DashedDividerView
    android:layout_width="match_parent"
    android:layout_height="2dp"
    />

またはXMLで属性を設定する

<com.your.package.app.DashedDividerView
    android:layout_width="match_parent"
    android:layout_height="2dp"
    app:dividerDirection="horizontal"
    app:dividerDashGap="2dp"
    app:dividerDashWidth="2dp"
    app:dividerDashColor="@color/light_gray"/>

2

これらの答えはどれもうまくいきませんでした。これらの回答のほとんどは、半透明の境界線を与えます。これを回避するには、コンテナを好みの色の別のコンテナでもう一度ラップする必要があります。次に例を示します。

こんな感じ

dashed_border_layout.xml

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="@color/black"
android:background="@drawable/dashed_border_out">
<LinearLayout
    android:layout_width="150dp"
    android:layout_height="50dp"
    android:padding="5dp"
    android:background="@drawable/dashed_border_in"
    android:orientation="vertical">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is&#10;Dashed Container"
        android:textSize="16sp" />
</LinearLayout>

dashed_border_in.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
    <shape>
        <corners android:radius="10dp" />
        <solid android:color="#ffffff" />
        <stroke
            android:dashGap="5dp"
            android:dashWidth="5dp"
            android:width="3dp"
            android:color="#0000FF" />
        <padding
            android:bottom="5dp"
            android:left="5dp"
            android:right="5dp"
            android:top="5dp" />
    </shape>
</item>

dashed_border_out.xml

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
    <shape>
        <corners android:radius="12dp" />
    </shape>
</item>


1

理由はわかりませんが、投票した回答がうまくいきません。私はこのように書いてうまくいきます。
カスタムビューを定義します。

public class XDashedLineView extends View {

private Paint   mPaint;
private Path    mPath;
private int     vWidth;
private int     vHeight;

public XDashedLineView(Context context) {
    super(context);
    init();
}

public XDashedLineView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public XDashedLineView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private void init() {
    mPaint = new Paint();
    mPaint.setColor(Color.parseColor("#3F577C"));
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setPathEffect(new DashPathEffect(new float[] {10,10}, 0));
    mPath = new Path();
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    this.vWidth = getMeasuredWidth();
    this.vHeight = getMeasuredHeight();
    mPath.moveTo(0, this.vHeight / 2);
    mPath.quadTo(this.vWidth / 2, this.vHeight / 2, this.vWidth, this.vHeight / 2);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawPath(mPath, mPaint);
}
}

次に、それをxmlで使用できます。

        <com.YOUR_PACKAGE_NAME.XDashedLineView
        android:layout_width="690dp"
        android:layout_height="1dp"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="620dp"/>

1

この問題を解決するために、カスタムビューのライブラリを作成しました。使用方法は非常に簡単です。詳細については、https://github.com/Comcast/DahDitを参照してください。次のように破線を追加できます。

<com.xfinity.dahdit.DashedLine
    android:layout_width="250dp"
    android:layout_height="wrap_content"
    app:dashHeight="4dp"
    app:dashLength="8dp"
    app:minimumDashGap="3dp"
    app:layout_constraintRight_toRightOf="parent"
    android:id="@+id/horizontal_dashes"/>

共有いただきありがとうございます。ユースケースに合わせて調整する必要がありますが、これはまさにカスタムビューを開始するために必要なものです。乾杯。

0

tier777と同様に、水平線のソリューションは次のとおりです。

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="-1dp">
        <shape android:shape="line">
            <stroke
                android:width="1dp"
                android:color="#111"
                android:dashWidth="8dp"
                android:dashGap="2dp"
                />
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>
</layer-list>

手がかりは<item android:top="-1dp">です。

古いデバイス(<= API 21)で破線を表示するには、ビューを作成する必要がありますandroid:layerType="software"Androidの破線の描画可能なICSバグを参照):

<?xml version="1.0" encoding="utf-8"?>
<View xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@drawable/dashed_line"
    android:layerType="software"
    />

また、同じビューを追加せずandroid:layerType="software"layout-v23パフォーマンスを向上させることもできますが、API 23のすべてのデバイスで動作するかどうかはわかりません。

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.