private void init() { //new 出一个画笔 paint1 = new Paint(); //设置画笔颜色 paint1.setColor(Color.WHITE); // 设置抗锯齿 paint1.setAntiAlias(true); // 填充 或 空 FILL - STROKE paint1.setStyle(Paint.Style.FILL); // paint1.setStyle(Paint.Style.STROKE); // 设置 宽 paint1.setStrokeWidth(5); paint2 = new Paint(); paint2.setColor(Color.WHITE); paint2.setStyle(Paint.Style.FILL); paint2.setAntiAlias(true); paint2.setStrokeWidth(5); // 透明度 setAlpha paint2.setAlpha(60); path1 = new Path(); path2 = new Path(); drawFilter = new PaintFlagsDrawFilter(0, Paint.FILTER_BITMAP_FLAG | Paint.ANTI_ALIAS_FLAG); }
@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); double Ω = 2 * Math.PI / getMeasuredWidth(); canvas.setDrawFilter(drawFilter); fai -= 0.1f; int A = getMeasuredHeight() / 2; path1.reset(); path2.reset(); path1.moveTo(getLeft(), getBottom()); path2.moveTo(getLeft(), getBottom()); for (int x = 0; x <= getMeasuredWidth(); x += 20) { // float y = Asin(Ωx+φ)+k float y1 = A * (float) Math.sin(Ω * x + fai) + A; float y2 = -A * (float) Math.sin(Ω * x + fai) + A; if (x > getMeasuredWidth() / 2 - 10 && x < getMeasuredWidth() / 2 + 10) { listener.onChanged(y2); } path1.lineTo(x,y1); path2.lineTo(x,y2); } path1.lineTo(getWidth(),getBottom()); path2.lineTo(getWidth(),getBottom()); canvas.drawPath(path1,paint1); canvas.drawPath(path2,paint2); postInvalidateDelayed(50); }
init(); } public interface onWaveChangeListener { void onChanged(float y); } private onWaveChangeListener listener; public void setOnWaveChangeListener(onWaveChangeListener listener) { this.listener = listener; }
private float fai = 0; private DrawFilter drawFilter;
private WaveView wv; private ImageView img; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); wv = findViewById(R.id.wv); img = findViewById(R.id.iv_img); WaveView.onWaveChangeListener listener = new WaveView.onWaveChangeListener() { @Override public void onChanged(float y) { RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) img.getLayoutParams(); layoutParams.setMargins(0,0,0, (int) y); img.setLayoutParams(layoutParams); } }; wv.setOnWaveChangeListener(listener);
<RelativeLayout android:layout_width="match_parent" android:layout_height="200dp" android:background="#FF0000"> <com.example.tp_pc.newview.WaveView android:id="@+id/wv" android:layout_width="match_parent" android:layout_height="40px" android:layout_alignParentBottom="true"/> <ImageView android:id="@+id/iv_img" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:src="@drawable/ic_launcher_background" android:layout_alignParentBottom="true"/> </RelativeLayout>