본문 바로가기

나의 플랫폼/안드로이드

[Android] View Background를 Rounded corner 형태로 반영

336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

RecyclerView나 ListView와 같은 여러 View가 묶어서 표현해야 하는 View에서 Corner 부분만 라운드를 시키고자 할때,

가장 쉽게 생각할 수 있는 부분이 Background에 Rounded된 이미지를 넣는 것으로 어느정도 해결이 된다.


하지만, 이 외에도 한가지 더 좋은 방법이 있다.

Rounded Corner 형태의 Drawable을 xml로 그리는 것이다.

그게 아래 소스이다.


<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFFFF"/>
<corners android:radius="10dip"/>
<padding android:left="0dp" android:top="0dp" android:right="0dp" android:bottom="0dp" />
</shape>


위 속성에서 corners 라는 값을 가지고 Corner에 Rounding 정도를 체크 할 수 있다.


## 위 형태로도 문제없이 동작이 가능 하면 좋지만, RecyclerView 나 ListView 등에서 row에 있는 View가 튀어 나오는 경우가 있습니다. 그럴 경우 아래와 같이 clip 을 한번 해줘보세요.


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

/**
* Created by Chcheung on 2016-01-12.
*/
public class RoundedRecyclerView extends RecyclerView {
private Path path;
public RoundedRecyclerView(Context context) {
super(context);
}

public RoundedRecyclerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}

public RoundedRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

@Override
protected void dispatchDraw(Canvas canvas) {
if (path == null) {
path = new Path();
path.addRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), 10, 10, Path.Direction.CW);
}
canvas.clipPath(path);
super.dispatchDraw(canvas);
}
}

그럼 문제없이 Child view들도 Clip 되는 것을 확인 할 수 있습니다.


참고로 ImageView와 같은 View에서는 dispatchDraw 대신 OnDraw 함수에서 해줘도 된다고 하네요.

만약에 안되면 OnDraw에 해보세요.


http://stackoverflow.com/a/7559233/3534559


참고하세요.