Last active
May 11, 2018 06:22
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<resources> | |
<declare-styleable name="RoundedRelativeLayout"> | |
<attr name="cornerRadius" format="dimension"/> | |
</declare-styleable> | |
</resources> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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