今天在网上Android上的水波纹效果,自己稍微研究了一下,其基本原理如下:
1 使用sin函数波形效果,sin函数解释。计算出y轴的一组数据
2 自定一个View,在View中使用canvas.drawLine()方法,使用第一步的数据绘制出一条sin函数的曲线。
3 在动画效果:将第一步计算出的y轴数据,循环左移N个数量单位,调用postInvalidate(); 方法重绘View就达到了相应的效果:
实现代码如下:
public class WaveViewActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(new WaveView(this)); } }
public class WaveView extends View{ float preX; float preY; private Path path; float[] yPositions; private int height; private int width; public Paint paint = null; public WaveView(Context context) { super(context);init(); } public WaveView(Context context, AttributeSet attrs) { super(context, attrs);init(); } public WaveView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr);init(); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) public WaveView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(); } private void init(){ paint = new Paint(Paint.DITHER_FLAG); paint.setColor(Color.BLUE); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(1); paint.setAntiAlias(true); paint.setDither(true); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); resetPositonY(); for(int i=0;i<width;i++){ canvas.drawLine(i,yPositions[i],i,height-400,paint); } postInvalidate(); } private void resetPositonY(){ float[] tmp =new float[width]; // arraycopy(Object src, int srcPos, //// Object dst, int dstPos, int length); System.arraycopy(yPositions, 0, tmp, 0, width); int offset=20; System.arraycopy(tmp, offset, yPositions, 0, width-offset); System.arraycopy(tmp, 0, yPositions, width-offset, offset); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); height=h; width=w; yPositions=new float[width]; // 将周期定为view总宽度 float mCycleFactorW = (float) (2 * Math.PI / width); for(int i=0;i<width;i++){ yPositions[i]= (float) (20*Math.sin(mCycleFactorW*i)+100); } } }
http://blog.csdn.net/qq_26787115/article/details/50688463
http://blog.csdn.net/jdsjlzx/article/details/44601239