Files
peko-android/app/src/main/java/com/yizhuan/erban/view/ShadowFrameLayout.java
2023-10-13 19:37:38 +08:00

93 lines
3.1 KiB
Java

package com.yizhuan.erban.view;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import com.yizhuan.erban.R;
/**
* @author wzq
*/
public class ShadowFrameLayout extends FrameLayout {
private Paint mShadowPaint;
private float mCornerRadius;
/**
* 只有上面有阴影
*/
private boolean mShadowTop;
private float mShadowRadius;
private RectF mRectF;
public ShadowFrameLayout(@NonNull Context context) {
this(context, null);
}
public ShadowFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public ShadowFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ShadowFrameLayout);
int shadowColor = typedArray.getColor(R.styleable.ShadowFrameLayout_shadowColor,
ContextCompat.getColor(context, R.color.color_1E686868));
int backgroundColor = typedArray.getColor(R.styleable.ShadowFrameLayout_backgroundColor, Color.WHITE);
mShadowRadius = typedArray.getDimension(R.styleable.ShadowFrameLayout_shadowRadius, 0);
mCornerRadius = typedArray.getDimension(R.styleable.ShadowFrameLayout_cornerRadius, 0);
mShadowTop = typedArray.getBoolean(R.styleable.ShadowFrameLayout_shadowTop, false);
typedArray.recycle();
mShadowPaint = new Paint();
mShadowPaint.setShadowLayer(mShadowRadius, 0, 0, shadowColor);
mShadowPaint.setAntiAlias(true);
mShadowPaint.setColor(backgroundColor);
setLayerType(LAYER_TYPE_SOFTWARE, null);
mRectF = new RectF();
}
@Override
public void setBackgroundColor(@ColorInt int color) {
mShadowPaint.setColor(color);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int measuredWidth = getMeasuredWidth();
int measuredHeight = getMeasuredHeight();
if (mShadowTop) {
// 矩形只有上方有阴影
mRectF.set(0, mShadowRadius, measuredWidth, measuredHeight + mCornerRadius);
} else {
// 环绕阴影
mRectF.set(mShadowRadius, mShadowRadius, measuredWidth - mShadowRadius, measuredHeight - mShadowRadius);
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
canvas.drawRoundRect(mRectF, mCornerRadius, mCornerRadius, mShadowPaint);
super.dispatchDraw(canvas);
}
}