[Android] 링 만들기

uuranus·2024년 7월 25일
0
post-thumbnail

링 그리기

  1. 가운데 원의 배경색을 바깥 배경이랑 동일하게 만든다.
    -> 내가 직접 사용하는 거라서 바깥 배경이 뭔지를 알면 상관없지만 나는 이걸 Shape으로 라이브러리화해서 배포할 거라서 알 수 없는 상황이다.
  2. 두 path사이의 차이점에 대해서만 그려기
    -> 이렇게 그려줄 수 있는 함수로 op메서드가 있었다.

Path.op 함수

  • operation의 줄임말인 함수인 것 같다.
  • 두 path에 대해서 특정 operaton을 수행해주는 함수이다.
path.apply {
    addOval(
        Rect(
            left = centerX - radius,
            top = centerY - radius,
            right = centerX + radius,
            bottom = centerY + radius
        )
    )

    op(
        path1 = this,
        path2 = Path().apply {
            addOval(
                Rect(
                    left = centerX - innerRadius,
                    top = centerY - innerRadius,
                    right = centerX + innerRadius,
                    bottom = centerY + innerRadius
                )
            )
        },
        operation = PathOperation.Difference
    )
}

PathOperation 옵션

옵션은 여러가지가 있다.

PathOperation.UionPathOperation.Intersection
두 path에 대해 합집합두 path간의 교집합
PathOperation.DifferencePathOperation.XOR
두 path의 차이가 나눈 부분을 그림교집합 외 나머지 부분들

최종 결과물

전체 코드

class RingShape(
    private val ringWidth: Dp,
) : Shape {
    override fun createOutline(
        size: Size,
        layoutDirection: LayoutDirection,
        density: Density,
    ): Outline {
        val path = Path()

        val centerX = size.width / 2
        val centerY = size.height / 2
        val radius = size.minDimension / 2

        val ringWidthPx = with(density) {
            ringWidth.toPx()
        }

        val innerRadius = radius - ringWidthPx

        path.apply {

            addOval(
                Rect(
                    left = centerX - radius,
                    top = centerY - radius,
                    right = centerX + radius,
                    bottom = centerY + radius
                )
            )

            op(
                path1 = this,
                path2 = Path().apply {
                    addOval(
                        Rect(
                            left = centerX - innerRadius,
                            top = centerY - innerRadius,
                            right = centerX + innerRadius,
                            bottom = centerY + innerRadius
                        )
                    )
                },
                operation = PathOperation.Xor
            )

        }

        return Outline.Generic(path)

    }
}

깃헙 링크

https://github.com/uuranus/compose-shapes

profile
Frontend Developer

0개의 댓글