GlassmorphismView in Android
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;
public class GlassmorphismView extends View {
private Paint mPaint;
private RectF mRectF;
private int mRadius = 60;
private int mShadowSize = 20;
private int mBackgroundColor = Color.parseColor("#80FFFFFF");
private int mGradientStartColor = Color.parseColor("#50FFFFFF");
private int mGradientEndColor = Color.parseColor("#00FFFFFF");
private int mStrokeWidth = 2;
private int mStrokeColor = Color.WHITE;
public GlassmorphismView(Context context) {
super(context);
init();
}
public GlassmorphismView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public GlassmorphismView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.FILL);
mRectF = new RectF();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
// Draw background
mPaint.setColor(mBackgroundColor);
canvas.drawRoundRect(mRectF, mRadius, mRadius, mPaint);
// Draw gradient
mPaint.setShader(new LinearGradient(centerX - mRadius, centerY - mRadius,
centerX + mRadius, centerY + mRadius,
mGradientStartColor, mGradientEndColor, Shader.TileMode.MIRROR));
canvas.drawRoundRect(mRectF, mRadius, mRadius, mPaint);
// Draw stroke
mPaint.setShader(null);
mPaint.setColor(mStrokeColor);
mPaint.setStrokeWidth(mStrokeWidth);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawRoundRect(mRectF, mRadius, mRadius, mPaint);
// Draw shadow
mPaint.setStyle(Paint.Style.FILL);
mPaint.setShadowLayer(mShadowSize, 0, 0, Color.BLACK);
canvas.drawRoundRect(mRectF, mRadius, mRadius, mPaint);
}
public void setBackgroundColor(int color) {
mBackgroundColor = color;
invalidate();
}
public void setGradientStartColor(int color) {
mGradientStartColor = color;
invalidate();
}
public void setGradientEndColor(int color) {
mGradientEndColor = color;
invalidate();
}
public void setStrokeColor(int color) {
mStrokeColor = color;
invalidate();
}
}