public class WaterView extends View { private Paint mBottomPaint; private Paint mTopPaint; private Path mPathBottom; private Path mPathTop; public WaterView(Context context) { this(context, null); } public WaterView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public WaterView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } float a; private void init(Context context) { mPathTop = new Path(); mPathBottom = new Path(); //创建两个画笔 mTopPaint = new Paint(); mTopPaint.setColor(Color.BLUE); mTopPaint.setAntiAlias(true); mBottomPaint = new Paint(); mBottomPaint.setColor(Color.YELLOW); mBottomPaint.setAntiAlias(true); mBottomPaint.setAlpha(60); //创建两个路径 //重写画 } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mPathTop.reset(); mPathBottom.reset(); //设置路径的起点与终点 mPathTop.moveTo(getLeft(), getBottom()); mPathBottom.moveTo(getLeft(), getBottom()); //设置路径轨迹 a -= 0.1f; double mY = Math.PI * 2 / getWidth(); for (int i = 0; i < getWidth(); i += 20) { float y, y0; y = (float) (10 * (Math.cos(mY * i + a)) + 20); y0 = (float) (10 * (Math.sin(mY * i + a)) + 10); mPathTop.lineTo(i, y); listener.onChange(y); mPathBottom.lineTo(i, y0); } //设置路径终点 mPathTop.lineTo(getRight(), getBottom()); mPathBottom.lineTo(getRight(), getBottom()); //设置好路径开始画 canvas.drawPath(mPathTop, mTopPaint); canvas.drawPath(mPathBottom, mBottomPaint); //ivaladate重复调用ondraw postInvalidateDelayed(20); } private onWaveChangeListener listener; public void setWaveChangeLitener(onWaveChangeListener litener) { this.listener = litener; } public interface onWaveChangeListener { void onChange(float y); } }
public class MainActivity extends AppCompatActivity { private ImageView ivLogo; private WaterView waveView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ivLogo = findViewById(R.id.iv_logo); waveView = findViewById(R.id.wave_view); final RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) ivLogo.getLayoutParams(); WaterView.onWaveChangeListener listener = new WaterView.onWaveChangeListener() { @Override public void onChange(float y) { layoutParams.setMargins(0, 0, 0, (int) y); ivLogo.setLayoutParams(layoutParams); } }; waveView.setWaveChangeLitener(listener); } }