느려요

진짜로

IT/Mobile

[Android/JAVA] 세로 점선 그리기

느이 2024. 2. 16. 10:45

세로로 점선을 그려야 하는데, xml을 이용해서 점선을 그리는 건 가로 점선만 되는 거 같다...

아무리 찾아도 못찾겠어서 인터넷을 찾아봤더니

 

가로 점선을 그리고 90도 돌려서 세로로 쓰라던데

 

0도
90도

아니 이게 뭐야 장난치나

 

90도 돌리는건 뷰 전체를 돌리는게 아니라 뷰 안에 그려진 내용을 90도 돌리는거라서

가로가 짧은 채로 돌리면 세로로 길게 되질 않는다.. 쓰읍...

 

그래서!

인터넷에서 줍줍한 소스를 정리해 보았다.

 

public class VerticalDashLine extends View {

    static public int ORIENTATION_HORIZONTAL = 0;
    static public int ORIENTATION_VERTICAL = 1;
    private Paint mPaint;
    private int orientation;

    public VerticalDashLine(Context context, AttributeSet attrs) {
        super(context, attrs);
        int dashGap, dashLength, dashThickness;
        int color;

        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.VerticalDashLine, 0, 0);

        try {
            dashGap = a.getDimensionPixelSize(R.styleable.VerticalDashLine_dashGap, 5); // 점과 점 사이의 거리
            dashLength = a.getDimensionPixelSize(R.styleable.VerticalDashLine_dashLength, 5); // 점의 길이
            dashThickness = a.getDimensionPixelSize(R.styleable.VerticalDashLine_dashThickness, 3); // 두께
            color = a.getColor(R.styleable.VerticalDashLine_color, 0xff000000); // 색
            orientation = a.getInt(R.styleable.VerticalDashLine_orientation, ORIENTATION_VERTICAL);
        } 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 VerticalDashLine(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);
        }
    }
}

 

그리고 attrs.xml에 아래 내용 추가

<declare-styleable name="VerticalDashLine">
    <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>

 

이제 내가 그리고 싶은 액티비티의 xml에 가서 VerticalDashLine 을 추가하고 사용하면 된다.

 

(출처를 잊어버려 죄삼다!)

반응형