如果要给按钮增加阴影效果,可以在drawable文件夹下通过layer-list标签来实现。但是这种方法对图片和文字却没有效果。但是Android系统提供了setShadowLayer()函数可以实现为图片和文字添加阴影。
setShadowLayer()
public void setShadowLayer(float radius, float dx, float dy, @ColorInt int shadowColor) {
setShadowLayer(radius, dx, dy, Color.pack(shadowColor));
}
- radius 模糊半径。数值越大越模糊,越小越清晰。如果为0,则阴影消失不见
- dx 阴影横向偏移距离,正值向右偏,负值向左偏
- dy 阴影纵向偏移距离,正值向下偏,负值向上偏
- color 阴影的颜色,但是对图片无效
class ShadowView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
val paint: Paint
val bitmap: Bitmap
var radius:Float
var dx:Float
var dy:Float
init {
radius = 10f
dx=10f
dy=10f
setLayerType(LAYER_TYPE_SOFTWARE, null)
paint = Paint()
paint.textSize = sp(22).toFloat()
paint.color = Color.RED
bitmap = BitmapFactory.decodeResource(resources, R.drawable.dog)
}
fun changeRadius(float: Float){
this.radius = radius
invalidate()
}
fun changeDx(dx: Float){
this.dx = dx
invalidate()
}
fun changeDy(dy: Float){
this.dy = dy
invalidate()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
paint.setShadowLayer(radius, dx, dy, Color.BLACK)
canvas.drawText("ABC", 100f, 100f, paint)
canvas.drawCircle(100f, 200f, 50f, paint)
canvas.drawBitmap(bitmap, 100f, 350f, paint)
}
}
如果要清除阴影的话则可以调用clearShadowLayer(),然后使view重绘即可。
setMaskFilter()
与阴影效果相似的还有一个发光效果。发光时边缘是什么颜色,发的光就是什么颜色。
public MaskFilter setMaskFilter(MaskFilter maskfilter) {
}
MaskFilter是一个类,不过里面什么逻辑都没有,需要用它的子类:
- BlurMaskFilter 实现发光效果。需要传两个参数,一个是半径,一个是枚举。枚举的取值有以下4种:
paint.maskFilter = BlurMaskFilter(28f,BlurMaskFilter.Blur.SOLID)
SOLID
paint.maskFilter = BlurMaskFilter(28f,BlurMaskFilter.Blur.NORMAL)
NORMAL
paint.maskFilter = BlurMaskFilter(28f,BlurMaskFilter.Blur.INNER)
INNER
paint.maskFilter = BlurMaskFilter(28f,BlurMaskFilter.Blur.OUTER)
OUTER
- EmbossMaskFilter 能够实现浮雕效果
paint.maskFilter = EmbossMaskFilter(floatArrayOf(4f,7f,22f),.9f,8f,12f)
给图片添加纯色阴影
其实阴影效果的产生就是获得一个跟原型一样的副本,然后对这个副本加上发光效果然后再偏移一段距离,就形成了所谓的阴影效果。
class ShadowView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
val paint: Paint
val bitmap: Bitmap
val alphaBitmap: Bitmap
init {
setLayerType(LAYER_TYPE_SOFTWARE, null)
paint = Paint()
paint.textSize = sp(22).toFloat()
paint.color = Color.RED
bitmap = BitmapFactory.decodeResource(resources, R.drawable.dog)
// 新建一张空白位图,并与原bitmap有一样的透明度
// 这张空白图的颜色则由画笔颜色决定
alphaBitmap = bitmap.extractAlpha()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
paint.setColor(Color.GRAY)
paint.maskFilter = BlurMaskFilter(28f,BlurMaskFilter.Blur.SOLID)
canvas.drawBitmap(alphaBitmap,100f,100f,paint)
canvas.translate(-5f,-5f)
paint.maskFilter = null
canvas.drawBitmap(bitmap, 100f, 100f, paint)
}
}
网友评论