1. 程式人生 > >Android貝塞爾曲線實現水波紋的效果

Android貝塞爾曲線實現水波紋的效果

前兩天朋友找我實現一個水波紋的效果,因為這塊一直沒做過,所以花了一上午時間研究一下,參考了網上的一些方法,得知Android還有Path.quadTo()這麼一個方法。

話不多說,程式碼如下:

public class MyView extends View implements View.OnClickListener {
    private int mRippleWeight;//一個波的週期長度
private  int mRippleCount;
    private int mScreenWidth;
    private int mScreenHeight;
    private int 
mCenterY;//需要展示的位置中線 private int mOffset; private Path mPath; private Paint mPaint; private ValueAnimator mValueAnimatior; public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG
); mPaint.setStyle(Paint.Style.STROKE); // mPaint.setStyle(Paint.Style.FILL_AND_STROKE);//如若需要下方帶顏色可用此樣式 mPaint.setStrokeWidth(8); mPaint.setAntiAlias(true); mPaint.setColor(Color.BLACK); } public MyView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs,
defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); mPath = new Path(); mScreenHeight = getMeasuredHeight(); mScreenWidth = getMeasuredWidth(); mCenterY = mScreenWidth / 2; mRippleWeight = mScreenHeight / 2; mRippleCount = Math.round(mScreenWidth / mRippleWeight + 2); setOnClickListener(this); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mPath.reset();//重置筆畫 mPath.moveTo(-mRippleWeight,mCenterY);//波走完重新的起點 /** * 如若波上下不夠大,僅需修改mCenterY + 400及mCenterY - 400, * 如若波左右不夠大,請把mRippleWeight值變大 */ for (int i = 0;i < mRippleCount;i++) { mPath.quadTo(-mRippleWeight * 3 / 4 + i * mRippleWeight + mOffset,mCenterY + 100,-mRippleWeight / 2 + i * mRippleWeight + mOffset,mCenterY); mPath.quadTo(-mRippleWeight / 4 + i * mRippleWeight + mOffset,mCenterY - 100,i * mRippleWeight + mOffset,mCenterY); } canvas.drawPath(mPath,mPaint); } @Override public void onClick(View v) { mValueAnimatior = ValueAnimator.ofInt(0, mRippleWeight); mValueAnimatior.setDuration(800); mValueAnimatior.setInterpolator(new LinearInterpolator()); mValueAnimatior.setRepeatCount(ValueAnimator.INFINITE); mValueAnimatior.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { mOffset = (int) animation.getAnimatedValue(); invalidate(); } }); mValueAnimatior.start(); } } 當然覺得還不明白的可以下載我寫的一個demo,連結如下:http://download.csdn.net/download/qq_28767927/9897370