Skip to content

Instantly share code, notes, and snippets.

@metaphore
Created December 9, 2015 18:32
Show Gist options
  • Save metaphore/3ea55ba0f6a425eb2c05 to your computer and use it in GitHub Desktop.
Save metaphore/3ea55ba0f6a425eb2c05 to your computer and use it in GitHub Desktop.
[Android] Frame layout with rounded corners
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RoundCornerFrameLayout">
<attr name="corner_radius" format="dimension"/>
</declare-styleable>
</resources>
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.widget.FrameLayout;
/**
* Frame layout that has rounded corners (it clips content too).
*
* @author Anton Chekulaev
*/
public class RoundCornerFrameLayout extends FrameLayout {
private final Path stencilPath = new Path();
private float cornerRadius = 0;
public RoundCornerFrameLayout(Context context) {
this(context, null);
}
public RoundCornerFrameLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RoundCornerFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray attrArray = context.obtainStyledAttributes(attrs, R.styleable.RoundCornerFrameLayout, 0, 0);
try {
cornerRadius = attrArray.getDimension(R.styleable.RoundCornerFrameLayout_corner_radius, 0f);
} finally {
attrArray.recycle();
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// compute the path
stencilPath.reset();
stencilPath.addRoundRect(0, 0, w, h, cornerRadius, cornerRadius, Path.Direction.CW);
stencilPath.close();
}
@Override
protected void dispatchDraw(@NonNull Canvas canvas) {
int save = canvas.save();
canvas.clipPath(stencilPath);
super.dispatchDraw(canvas);
canvas.restoreToCount(save);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment