《自定义view》
public class WaterView extends View {
private Paint paint;
private Path path;
private float mX;
public WaterView(Context context) {
super(context);
init(context);
}
public WaterView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context);
}
//初始化画笔路径
private void init(Context context) {
//初始化路径
path = new Path();
paint = new Paint();//画笔
paint.setColor(Color.RED);//画笔颜色
paint.setStrokeWidth(5);//画笔的粗细
paint.setAntiAlias(true);//设置是否使用抗锯齿功能,会消耗较大资源,绘制图形速度会变慢
}
//绘制方法
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
path.reset();//路径重置
path.moveTo(getLeft(), 350); //记录起始位置
//记录波动位置
float mpl = (float) (Math.PI*4/getRight());//获取每一个宽度所占的度数
mX -= 0.1f;
for (int x = 0; x<=getRight(); x+=20) {
path.lineTo(x, (float) (10*Math.cos(mpl*x+mX)+100));//记录从左向右的x作弊哦
}
path.lineTo(getRight(), 350); //记录结束位置
//通过canvas绘制
canvas.drawPath(path, paint);
postInvalidateDelayed(20);//定时刷新
}
}
《布局》
<com.bawei.mydonghua.WaterView
android:id="@+id/water_view"
android:layout_width=“match_parent”
android:layout_height=“match_parent” />
《MainActivity 》
public class MainActivity extends AppCompatActivity {
private WaterView water;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
water = findViewById(R.id.water_view);
}
}