Android波浪效果自定义View实现

2018-02-13  本文已影响0人  Coder_吴磊

个人原创文章,请尊重原创,转载请注明出处:吴磊的简书:http://www.jianshu.com/p/a4c29ec5712f

前言

最近在Github上看到@1139618418 大神写了一个波浪效果的View,发现效果非常酷炫,但是代码上有很大的优化空间,就照着思路自己撸了一个。留着以后备用。

需求

实现一个类似于波浪效果的自定义view,并且可以提供一个波浪起伏变化距离的接口。
直接上效果图:


20180213_021953_20180213092027.gif

实现

class SugarWaveView : View {

    private val mAbovePath = Path()
    private val mBelowPath = Path()
    private val mAbovePaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val mBelowPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val drawFilter = PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG)
    private var start = 0.0f //初相  正弦函数:y=Asin(ωx+φ)+k
    private var range = 0.0  //周期,决定屏幕范围内波浪的数量
    var cycle = 2    //周期乘数,自定义
    var peakHeight = 8.0f //波浪高度,dp
    var waveColor: Int = Color.WHITE
    var waveAlpha = 80
    var listenr:OnWaveChangeListener?=null


    constructor(context: Context) : super(context)

    constructor(context: Context, attr: AttributeSet) : super(context, attr) {
        val ta = context.obtainStyledAttributes(attr, R.styleable.SugarWaveView)
        waveColor = ta.getColor(R.styleable.SugarWaveView_waveColor, ContextCompat.getColor(context, R.color.colorPrimaryDark))
        waveAlpha = ta.getInt(R.styleable.SugarWaveView_backWaveAlpha, 80)
        cycle = ta.getInt(R.styleable.SugarWaveView_cycle, 2)
        peakHeight = ta.getDimension(R.styleable.SugarWaveView_peakHeight, 8.0f)
        ta.recycle()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        range = cycle * Math.PI / width
    }

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        mAbovePaint.isAntiAlias = true
        mAbovePaint.style = Paint.Style.FILL
        mAbovePaint.color = waveColor
        mBelowPaint.isAntiAlias = true
        mBelowPaint.style = Paint.Style.FILL
        mBelowPaint.color = waveColor
        mBelowPaint.alpha = waveAlpha

    }


    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas!!.drawFilter = drawFilter
        mAbovePath.reset()//每次onDraw前初始化path,above为不透明波浪,below为透明的波浪
        mBelowPath.reset()
        start -= 0.1f//初相
        var y1: Float
        var y2: Float
        mAbovePath.moveTo(left.toFloat(), bottom.toFloat())
        mBelowPath.moveTo(left.toFloat(), bottom.toFloat())
        for (x in 0..width step 20) {//kotlin写法  java为for(int i=0;i<=getWidth();i+=20)
            /**
             * 此处根据X不断变化,算出Y的值,得到正弦、余弦曲线的坐标点,最后一个个连接起来
             */
            y1 = (peakHeight * Math.cos(range * x + start) + peakHeight + 10).toFloat()
            y2 = (peakHeight * Math.sin(range * x + start) + peakHeight).toFloat()
            mAbovePath.lineTo(x.toFloat(), y1)
            mBelowPath.lineTo(x.toFloat(), y2)
        }
        val middleY = (peakHeight * Math.cos(range * width/2 + start) + peakHeight).toFloat()
        listenr?.onWaveHeightChange(middleY)
        mAbovePath.lineTo(right.toFloat(), bottom.toFloat())
        mBelowPath.lineTo(right.toFloat(), bottom.toFloat())
        canvas.drawPath(mAbovePath, mAbovePaint)
        canvas.drawPath(mBelowPath, mBelowPaint)
        postInvalidateDelayed(10)//延迟10ms重新绘制
    }

    interface OnWaveChangeListener{
        fun onWaveHeightChange(y:Float)
    }
  1. 需要2个构造函数。第一个为只有上下文的构造,用在代码中动态添加。第二个用于在xml布局中设置属性的构造。
    那么怎么获取xml布局中的属性呢,其实很简单,首先在value/attrs.xml中添加各属性名称,无此文件新建即可,然后直接在xml中使用即可:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="SugarWaveView">
        <attr name="waveColor" format="color"/>
        <attr name="backWaveAlpha" format="integer"/>
        <attr name="cycle" format="integer"/>
        <attr name="peakHeight" format="dimension"/>
    </declare-styleable>
</resources>

<com.wulei.uikit.SugarWaveView
    android:id="@+id/waveview"
    android:layout_width="match_parent"
    android:layout_height="500dp"
    android:layout_alignParentBottom="true"
    app:peakHeight="5dp"
    app:waveColor="#ffffff" />
  1. 在构造函数中获取xml设置的自定义属性,首先拿到typedArray对象 val ta = context.obtainStyledAttributes(attr, R.styleable.SugarWaveView) ,然后通过在attrs定义好的名称,一个个获取,敲黑板:获取完记得recycle():
    constructor(context: Context, attr: AttributeSet) : super(context, attr) {
        val ta = context.obtainStyledAttributes(attr, R.styleable.SugarWaveView)
        waveColor = ta.getColor(R.styleable.SugarWaveView_waveColor, ContextCompat.getColor(context, R.color.colorPrimaryDark))
        waveAlpha = ta.getInt(R.styleable.SugarWaveView_backWaveAlpha, 80)
        cycle = ta.getInt(R.styleable.SugarWaveView_cycle, 2)
        peakHeight = ta.getDimension(R.styleable.SugarWaveView_peakHeight, 8.0f)
        ta.recycle()
    }
  1. 拿到屏幕的宽度,只有拿到宽度后才知道曲线需要画多长,拿宽度比较合适的时机是在onMeasure之后,在这之前,是拿不到的。
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        range = cycle * Math.PI / width // range:周期,决定屏幕内波浪的数量,cycle:常数,通过改变它来改成range,width在java中为getWidth()
    }
  1. 根据构造函数中拿到的自定义属性,来初始化画笔,mBelowPaint用于画出一个半透明的波浪,看起来有交错感,此处参照了原作者的思路:
    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        mAbovePaint.isAntiAlias = true
        mAbovePaint.style = Paint.Style.FILL
        mAbovePaint.color = waveColor
        mBelowPaint.isAntiAlias = true
        mBelowPaint.style = Paint.Style.FILL
        mBelowPaint.color = waveColor
        mBelowPaint.alpha = waveAlpha
    }
  1. OK,下面是最重要的画曲线部分。首先,给定一个初始的初相,画出正弦曲线,正弦曲线的画法为:通过改变x轴的坐标,不断通过y=Asin(ωx+φ)+k来算出y轴坐标。每N个像素算出一个点,将这些点连接起来,此处需要使用到path,然后不断的lineTo(x,y),当点足够密集的时候,看起来就是曲线了。代码如下:
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas!!.drawFilter = drawFilter
        mAbovePath.reset()//每次onDraw前初始化path,above为不透明波浪,below为透明的波浪
        mBelowPath.reset()
        start -= 0.1f//初相
        var y1: Float
        var y2: Float
        mAbovePath.moveTo(left.toFloat(), bottom.toFloat())
        mBelowPath.moveTo(left.toFloat(), bottom.toFloat())
        for (x in 0..width step 20) {//kotlin写法  java为for(int i=0;i<=getWidth();i+=20)
            /**
             * 此处根据X不断变化,算出Y的值,得到正弦、余弦曲线的坐标点,最后一个个连接起来
             */
            y1 = (peakHeight * Math.cos(range * x + start) + peakHeight + 10).toFloat()
            y2 = (peakHeight * Math.sin(range * x + start) + peakHeight).toFloat()
            mAbovePath.lineTo(x.toFloat(), y1)
            mBelowPath.lineTo(x.toFloat(), y2)
        }
        val middleY = (peakHeight * Math.cos(range * width/2 + start) + peakHeight).toFloat()
        listenr?.onWaveHeightChange(middleY)
        mAbovePath.lineTo(right.toFloat(), bottom.toFloat())
        mBelowPath.lineTo(right.toFloat(), bottom.toFloat())
        canvas.drawPath(mAbovePath, mAbovePaint)
        canvas.drawPath(mBelowPath, mBelowPaint)
        postInvalidateDelayed(10)//延迟10ms重新绘制
    }

然后,通过postInvalidateDelayed来延迟一段时间重新绘制,此时只需改变初相,图像就会得到移动的效果。

  1. 最后,定义一个返回中心位置波浪Y轴变化的接口,用于实现其他控件的联动:
    interface OnWaveChangeListener{
        fun onWaveHeightChange(y:Float)
    }

到这里就完成了整个自定义View的编写、使用。完整代码及Demo可以在我的Github中查看。如发现有改进之处,望指正,万分感谢!

个人原创文章,请尊重原创,转载请注明出处:吴磊的简书:http://www.jianshu.com/p/a4c29ec5712f

欢迎联系我:
Github:https://github.com/MondeoWu/
E-mail:331948214@qq.com
QQ:331948214

上一篇下一篇

猜你喜欢

热点阅读