Skip to content

Instantly share code, notes, and snippets.

@chowaikong
Created June 8, 2017 08:30
Show Gist options
  • Save chowaikong/3215e139f39bb48a40afdd0ba3489aba to your computer and use it in GitHub Desktop.
Save chowaikong/3215e139f39bb48a40afdd0ba3489aba to your computer and use it in GitHub Desktop.
class WaveView(context: Context, attrs: AttributeSet) : View(context, attrs) {
private val mAbovePath: Path = Path()
private val mBelowWavePath: Path = Path()
private val mAboveWavePaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val mBelowWavePaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val mDrawFilter: DrawFilter = PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
private var φ: Float = 0.toFloat()
init {
mAboveWavePaint.isAntiAlias = true
mAboveWavePaint.style = Paint.Style.FILL
mAboveWavePaint.color = Color.WHITE
mBelowWavePaint.isAntiAlias = true
mBelowWavePaint.style = Paint.Style.FILL
mBelowWavePaint.color = Color.WHITE
mBelowWavePaint.alpha = 205
}
override fun onDraw(canvas: Canvas) {
canvas.drawFilter = mDrawFilter
mAbovePath.reset()
mBelowWavePath.reset()
φ -= 0.1f
var y1: Float
var y2: Float
val ω = 2 * Math.PI / width
mAbovePath.moveTo(left.toFloat(), bottom.toFloat())
mBelowWavePath.moveTo(left.toFloat(), bottom.toFloat())
var x = 0f
while (x <= width) {
/**
* y=Asin(ωx+φ)+k
* A—振幅越大,波形在y轴上最大与最小值的差值越大
* ω—角速度, 控制正弦周期(单位角度内震动的次数)
* φ—初相,反映在坐标系上则为图像的左右移动。这里通过不断改变φ,达到波浪移动效果
* k—偏距,反映在坐标系上则为图像的上移或下移。
*/
y1 = (20 * Math.cos(ω * x + φ) + 20).toFloat()
y2 = (20 * Math.sin(ω * x + φ) + 20).toFloat()
mAbovePath.lineTo(x, y1)
mBelowWavePath.lineTo(x, y2)
x += 30f
}
mAbovePath.lineTo(right.toFloat(), bottom.toFloat())
mBelowWavePath.lineTo(right.toFloat(), bottom.toFloat())
canvas.drawPath(mAbovePath, mAboveWavePaint)
canvas.drawPath(mBelowWavePath, mBelowWavePaint)
postInvalidateDelayed(40)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment