栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

android 使用setShadowLayer创建简单的阴影

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

android 使用setShadowLayer创建简单的阴影

android 使用setShadowLayer创建简单的阴影

现在Android项目使用阴影的需求越来越多了,下面我价绍一下创建阴影的代码。一般来说ui切图的阴影虽然好看舒服一点,但是不利于动态定制,如果代码里能自己定制多好啊。主要的使用的api是paint.setShaodwLayout。

class SimpleShadowBuilder {

    private var shadowRadius: Float = 2f.dpToPxFloat()
    private var solidColor: Int = Color.WHITE
    private var shadowColor: Int = Color.DKGRAY
    private var dx = 0f
    private var dy = 0f

    private var width: Int = -1
    private var height: Int = -1

    private var shape: Shape = OvalShape()

    fun setShadowRadius(shadowRadius: Float): SimpleShadowBuilder {
        this.shadowRadius = shadowRadius.coerceAtLeast(0f)
        return this
    }

    fun setShadowColor(color: Int): SimpleShadowBuilder {
        shadowColor = color
        return this
    }

    fun setSolidColor(color: Int): SimpleShadowBuilder {
        this.solidColor = color
        return this
    }

    fun setShadowDx(dx: Float): SimpleShadowBuilder {
        this.dx = dx
        return this
    }

    fun setShadowDy(dy: Float): SimpleShadowBuilder {
        this.dy = dy
        return this
    }

    fun width(width: Int): SimpleShadowBuilder {
        this.width = width
        return this
    }

    fun height(height: Int): SimpleShadowBuilder {
        this.height = height
        return this
    }

    fun setShape(shape: Shape): SimpleShadowBuilder {
        this.shape = shape
        return this
    }

    fun roundShape(cornerRadius: Float): SimpleShadowBuilder {
        val outerRadius = floatArrayOf(
            cornerRadius, cornerRadius, cornerRadius, cornerRadius,
            0f, 0f, 0f, 0f
        )
        this.shape = RoundRectShape(outerRadius, null, null)
        return this
    }

    private fun build(): Drawable {
        val shadowDrawable = ShapeDrawable()
        shadowDrawable.paint.setShadowLayer(
            shadowRadius,
            dx,
            dy,
            shadowColor
        )

        shadowDrawable.paint.style = Paint.Style.FILL
        shadowDrawable.paint.color = solidColor
        shadowDrawable.shape = this.shape

        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            InsetDrawable(shadowDrawable, shadowRadius)
        } else {
            InsetDrawable(shadowDrawable, shadowRadius.toInt())
        }
    }

    fun into(view: View) {

        val parent = view.parent as? ViewGroup
        parent?.clipChildren = false
        parent?.clipToPadding = false

        view.setLayerType(View.LAYER_TYPE_SOFTWARE, null)
        view.background = build()
    }
}

下面贴上使用效果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/340314.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号