:)
阴影绘制需要的知识点
- 硬件加速
- Paint对象的setShadowLayer方法
android硬件加速
- Application级别开启硬件加速
<application android:hardwareAccelerated="true"/>
- Activity级别开启硬件加速
<activity android:hardwareAccelerated="true">
- Window级别开启硬件加速
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED
);
-
View级别开启硬件加速
myView.setLayerType(View.LAYER_TYPE_*, null);
setShadowLayer
思路来自一个开源库
https://github.com/yingLanNull/ShadowImageView
解析上面那个开源库
- 这个库的主要代码就一个自定义的控件ShadowImageView(继承RelativeLayout)
public class ShadowImageView extends RelativeLayout
- 实现思路就是先给这个控件绘制一个带阴影的背景,然后在给这个控件添加一个ImageView的子控件
- 构造方法的实现
public ShadowImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setPadding(80, 40, 80, 120); //设置一个padding用来绘制阴影背景
setGravity(Gravity.CENTER);
setLayerType(LAYER_TYPE_SOFTWARE, null); //开启硬件加速
//添加一个imageView的子控件
RoundImageView roundImageView = new RoundImageView(context);
roundImageView.setScaleType(ImageView.ScaleType.FIT_XY);
if (imageresource == -1) {
roundImageView.setImageResource(android.R.color.transparent);
} else {
roundImageView.setImageResource(imageresource);
}
addView(roundImageView);
}
- 背景的绘制方法dispatchDraw(简化)
@Override
protected void dispatchDraw(Canvas canvas) {
//初始化一个绘制背景的画笔
Paint shadowPaint = new Paint();
shadowPaint.setColor(Color.WHITE);
shadowPaint.setStyle(Paint.Style.FILL);
shadowPaint.setAntiAlias(true);
//计算阴影的偏移量 和 给画笔设置阴影
int radius = view.getHeight() / 12 > 40 ? 40 : view.getHeight() / 12;
int shadowColor = view.getHeight() / 16 > 28 ? 28 : view.getHeight() / 16;
shadowPaint.setShadowLayer(radius, 0, shadowColor, getDarkerColor(rgb));
//确定阴影的的整个大小
RectF rectF = new RectF(view.getX() + (view.getWidth() / 20), view.getY(), view.getX() + view.getWidth() - (view.getWidth() / 20), view.getY() + view.getHeight() - ((view.getHeight() / 40)));
canvas.drawRoundRect(rectF, shadowRound, shadowRound, shadowPaint);
canvas.save();
super.dispatchDraw(canvas);
}
- 阴影颜色的获取(上面使用的是getDarkerColor方法,这里面有一个小技巧就是HSV模型)
public int getDarkerColor(int color) {
float[] hsv = new float[3];
Color.colorToHSV(color, hsv);
hsv[1] = hsv[1] + 0.1f;
hsv[2] = hsv[2] - 0.1f;
int darkerColor = Color.HSVToColor(hsv);
return darkerColor;
}
简单说一下HSV
- 平时我们说颜色一般都是RGB,R分量表示红色,G绿色,、B蓝色
- 而HSV也是用来表示颜色的,只是H表示色调(0 ~ 360),S表示饱和度(0 ~ 1),V表示明度(0 ~ 1)
Nothing is certain in this life. The only thing i know for sure is that. I love you and my life. That is the only thing i know. have a good day