新建一个工具类
继承View实现 onMeasure() onLayout() OnDraw()三个方法
具体实现如下:
public class Views extends View {
private Paint paint;
private Path path;
float A=8f;
float w;
float k=0f;
float f;
float y;
private Paint paint1;
private Path path1;
float y1;
public Views(Context context) {
super(context);
initView();
}
public Views(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public Views(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initView();
}
private void initView(){
//创建一个画笔
paint=new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
path=new Path();
//创建一个画笔
paint1=new Paint(Paint.ANTI_ALIAS_FLAG);
paint1.setColor(Color.BLUE);
paint1.setAntiAlias(true);
paint1.setStyle(Paint.Style.FILL);
paint1.setAlpha(80);
path1=new Path();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
path.reset();
path1.reset();
path.moveTo(getLeft(),getBottom());
path1.moveTo(getLeft(),getBottom());
w= (float) (2*Math.PI/getWidth());
f-=0.1f;
for (int x=0;x<=getWidth();x+=20){
y= (float) (A*Math.sin(w*x+f));
y1= (float) (A*Math.cos(w*x+f)+8);
path.lineTo(x,y);
path1.lineTo(x,y1);
animations.getY(y);
}
path.lineTo(getRight(),getBottom());
path1.lineTo(getRight(),getBottom());
canvas.drawPath(path,paint);
canvas.drawPath(path1,paint1);
postInvalidateDelayed(20);
}
private Animations animations;
public void setAnimations(Animations animations) {
this.animations= animations;
}
public interface Animations{
void getY(float y);
}
}
主页面布局
<FrameLayout
android:layout_width=“match_parent”
android:layout_height=“300dp”
android:layout_alignParentTop="true">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="122dp"
android:layout_marginLeft="122dp"
android:layout_marginTop="14dp"
android:src="@drawable/ic_launcher_background" />
<com.bwie.wo.wangshuilong20190308.view.activity.Views
android:id="@+id/views"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="155dp" />
</FrameLayout>
MainActivity
initView();
private void initView(){
lp=new FrameLayout.LayoutParams(-2,-2);
lp.gravity=Gravity.CENTER;
views.setAnimations(new Views.Animations() {
@Override
public void getY(float y) {
lp.setMargins(0,-20,0, (int) (y+2));
imageView.setLayoutParams(lp);
}
});
}