Skip to content

Instantly share code, notes, and snippets.

@jerrellmardis
Last active May 11, 2018 06:22
Show Gist options
  • Save jerrellmardis/9240278 to your computer and use it in GitHub Desktop.
Save jerrellmardis/9240278 to your computer and use it in GitHub Desktop.
A {@link android.widget.RelativeLayout} that supports rounded corners and proper child view clipping. Perfect for situations where you have full bleed images that you want clipped to the bounds of this layout.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RoundedRelativeLayout">
<attr name="cornerRadius" format="dimension"/>
</declare-styleable>
</resources>
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
/**
* A {@link android.widget.RelativeLayout} that supports rounded corners.
*
* @author Jerrell Mardis
*/
public class RoundedRelativeLayout extends RelativeLayout {
private Path mPath = new Path();
private float mRadius = 0;
public RoundedRelativeLayout(Context context) {
super(context);
setWillNotDraw(false);
}
public RoundedRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
setWillNotDraw(false);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundedRelativeLayout);
try {
mRadius = a.getDimension(R.styleable.RoundedRelativeLayout_cornerRadius, 0);
} finally {
a.recycle();
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mPath = new Path();
mPath.addRoundRect(new RectF(mRadius, mRadius, w, h), mRadius, mRadius, Path.Direction.CW);
mPath.close();
}
@Override
public void draw(Canvas canvas) {
canvas.save();
canvas.clipPath(mPath);
super.draw(canvas);
canvas.restore();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(getMeasuredWidth(), getMeasuredHeight());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment