-
-
Save PhongHuynh93/83366581bbe1ffa82067083f41a43a41 to your computer and use it in GitHub Desktop.
Android Rounded Corner Layout
This file contains hidden or 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
// This layout will display its children with rounded corners | |
// It works with Glide image library placeholders and animations | |
// It assumes your background is a solid color. If you need the corners to be truly transparent, | |
// this solution will not work for you. | |
package com.myapp.ui; | |
import android.content.Context; | |
import android.graphics.Bitmap; | |
import android.graphics.Canvas; | |
import android.graphics.Color; | |
import android.graphics.Paint; | |
import android.graphics.PorterDuff; | |
import android.graphics.PorterDuffXfermode; | |
import android.graphics.RectF; | |
import android.util.AttributeSet; | |
import android.widget.RelativeLayout; | |
public class RoundedCornerLayout extends RelativeLayout { | |
private Bitmap maskBitmap; | |
private Paint paint; | |
private float cornerRadius; | |
public RoundedCornerLayout(Context context) { | |
super(context); | |
init(context, null, 0); | |
} | |
public RoundedCornerLayout(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
init(context, attrs, 0); | |
} | |
public RoundedCornerLayout(Context context, AttributeSet attrs, int defStyle) { | |
super(context, attrs, defStyle); | |
init(context, attrs, defStyle); | |
} | |
private void init(Context context, AttributeSet attrs, int defStyle) { | |
paint = new Paint(Paint.ANTI_ALIAS_FLAG); | |
setWillNotDraw(false); | |
} | |
@Override | |
public void draw(Canvas canvas) { | |
super.draw(canvas); | |
if (maskBitmap == null) { | |
// This corner radius assumes the image width == height and you want it to be circular | |
// Otherwise, customize the radius as needed | |
cornerRadius = canvas.getWidth() / 2; | |
maskBitmap = createMask(canvas.getWidth(), canvas.getHeight()); | |
} | |
canvas.drawBitmap(maskBitmap, 0f, 0f, paint); | |
} | |
private Bitmap createMask(int width, int height) { | |
Bitmap mask = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); | |
Canvas canvas = new Canvas(mask); | |
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); | |
paint.setColor(Color.WHITE); // TODO set your background color as needed | |
canvas.drawRect(0, 0, width, height, paint); | |
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); | |
canvas.drawRoundRect(new RectF(0, 0, width, height), cornerRadius, cornerRadius, paint); | |
return mask; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment