贝塞尔曲线自定义视图的阴影效果

时间:2018-02-25 19:59:36

标签: android android-canvas android-custom-view

如何在弯曲的自定义视图组底部添加阴影效果?我正在实现一个bezier曲线路径,以将底部曲线添加到矩形形状。我想添加一个平行于弯曲底边的底部阴影,有人可以建议这样做吗?

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

目前看来enter image description here

1 个答案:

答案 0 :(得分:1)

你可以做的是在原始的下面绘制相同的形状,但是使用BlurMaskFilter,我稍微重构了你的类,但结果似乎很有希望

class CurveContainer @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
    : ConstraintLayout(context, attrs, defStyleAttr) {

    private val mainPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = 0xffff0000.toInt()
        style = Paint.Style.FILL
    }

    private val shadowPaint = Paint(Paint.ANTI_ALIAS_FLAG.or(Paint.DITHER_FLAG)).apply {
        color = 0xff000000.toInt()
        style = Paint.Style.FILL
        maskFilter = BlurMaskFilter(32f, BlurMaskFilter.Blur.OUTER)
    }

    private val mainPath = Path()
    private val shadowPath = Path()

    private var bezierEdgeY = 0f
    private var bezierHandleY = 0f

    private var edgePercentY = 0.25f
    private var handlePercentY = 0.5f

    init {
        setWillNotDraw(false)
        setLayerType(View.LAYER_TYPE_SOFTWARE, shadowPaint)
    }

    fun setBezierPositionPercent(edgePercentY: Float, handlePercentY: Float) {
        this.edgePercentY = edgePercentY
        this.handlePercentY = handlePercentY
        computePath(width.toFloat(), height.toFloat())
    }

    private fun computePath(width: Float, height: Float) {
        bezierEdgeY = height * 0.25f
        bezierHandleY = height * 0.5f

        val halfWidth = width / 2

        shadowPath.reset()
        shadowPath.moveTo(0f, 0f)
        shadowPath.lineTo(width, 0f)
        shadowPath.lineTo(width, bezierEdgeY)
        shadowPath.quadTo(halfWidth, bezierHandleY, 0f, bezierEdgeY)
        shadowPath.lineTo(0f, 0f)

        mainPath.reset()
        mainPath.moveTo(0f, 0f)
        mainPath.lineTo(width, 0f)
        mainPath.lineTo(width, bezierEdgeY)
        mainPath.quadTo(halfWidth, bezierHandleY, 0f, bezierEdgeY)
        mainPath.lineTo(0f, 0f)

        invalidate()
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        computePath(w.toFloat(), h.toFloat())
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawPath(shadowPath, shadowPaint)
        canvas.drawPath(mainPath, mainPaint)
    }
}

curve with shadow