4

Android 自定义 view 中 canvas 阴影绘制方法

 3 years ago
source link: http://i.lckiss.com/?p=7172
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Android 自定义 view 中 canvas 阴影绘制方法

2021-07-10

这周下来一个蜘蛛网图(或者雷达网图)的绘制需求,本身这种网图也不算复杂就是画几个圆,分几个方向连下点,再根据数据比例确定网大小。但需求里来了个相对复杂的设计,就是阴影。对于 Android 来说,阴影往往不是很好处理。

主要方法:

# Paint 方法
public void setShadowLayer(float radius, float dx, float dy, int color)

参数很好理解,按设计稿填即可,但最后一个参数的颜色值测试了是不生效的,颜色值需要对 paint 本身的 color 进行修改,此外透明度不要使用 paint 的 alpha 属性,直接对颜色值的 alpha 通道进行修改。那么现在大概率可以画出一块阴影。往往 UI 的要求是拟真的,所以一块肯定是不行,就需要镂空。镂空好说啊,用 path 画的直接用 clipPath 即可,其他类推。

对于 api >= 26 的直接使用:

clipOutPath(mPath) 

小于的则使用:

clipPath(mPath, Region.Op.DIFFERENCE)

所以整体的逻辑代码大概是:

canvas.save()
paint.setShadowLayer()
if(api >= 26){
    canvas.clipOutPath(path)
}else{
    canvas.clipPath(path, Region.Op.DIFFERENCE)
}
canvas.drawPath(path,paint)
canvas.restore()

这样就不会影响其他图层的透明效果了,只留下那点阴影。图就不上了,也不是什么复杂的东西。

更详细的请参考:

setShadowLayer阴影与SetMaskFilter发光效果

Canvas中的裁剪师讲解与实战


  • 2021051300031389.jpg

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK