android自定义view波浪曲线
最近需求要再登录页面添加俩条动态波浪线,参考大神们的Demo解决了需求,废话不多说直接上代码!
一、自定义View
public class DoubleWaveView extends View {
private Paint mPaint;
private Path mPath;
private int width, height;
private int dx;
public DoubleWaveView(Context context, int width, int height) {
super(context);
this.width = width;
this.height = height;
init();
}
public DoubleWaveView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public DoubleWaveView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private void init() {
mPath = new Path();
// 初始绘制波纹的画笔
mPaint = new Paint();
// 设置风格为实线
mPaint.setStyle(Paint.Style.STROKE);
// mPaint.setStyle(Paint.Style.FILL_AND_STROKE);//填充满
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//重置绘制路线,即隐藏之前绘制的轨迹
mPath.reset();
// 去除画笔锯齿
mPaint.setAntiAlias(true);
// 设置画笔颜色
mPaint.setColor(Color.parseColor("#F333EC"));
//mPath绘制的绘制起点高度
mPath.moveTo(-width + dx, height / 3 * 2);
for (int i = 0; i < 3; i++) {
//画贝塞尔曲线
mPath.rQuadTo(width / 5, -70, width / 2, 0);
mPath.rQuadTo(width / 5, 70, width / 2, 0);
}
//填充形成波浪效果
// mPath.lineTo(width, height);
// //两点连成直线
// mPath.lineTo(0, height);
// //回到初始点形成封闭的曲线
// mPath.close();
canvas.drawPath(mPath, mPaint);
mPath.reset();
mPaint.setColor(Color.parseColor("#5733F3"));
mPath.moveTo(-width + dx, height / 3 * 2);
for (int i = 0; i < 3; i++) {
mPath.rQuadTo(width / 4, 70, width / 2, 0);
mPath.rQuadTo(width / 4, -70, width / 2, 0);
}
// mPath.lineTo(width, height);
// mPath.lineTo(0, height);
// mPath.close();
// 开始绘制
canvas.drawPath(mPath, mPaint);
}
public void startAnimation() {
// 属性动画
ValueAnimator valueAnimator = ValueAnimator.ofInt(0, width);// 从某个值变化到某个值
valueAnimator.setDuration(2000);//动画时间
valueAnimator.setRepeatCount(ValueAnimator.INFINITE);// 设置播放次数。如果为ValueAnimator.INFINITE表示无限播放下去
valueAnimator.setInterpolator(new LinearInterpolator());//动画抛物线匀速运动
//如果不加,ValueAnimator或是AnimatorSet.start时改动画对象不能播放
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
dx = (int) animation.getAnimatedValue();//得到当前值
invalidate();//刷新View
}
});
valueAnimator.start();//启动动画
}
}
二、MainActivity
public class MainActivity extends AppCompatActivity {
private FrameLayout rootView;
private DoubleWaveView waveView;
private int width,height;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.doublewaveview);
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
width = wm.getDefaultDisplay().getWidth();
height = wm.getDefaultDisplay().getHeight();
initWaveView();
}
private void initWaveView() {
rootView = (FrameLayout) findViewById(R.id.rootView);
waveView = new DoubleWaveView(this, width, height);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width, height);
rootView.addView(waveView, params);
waveView.startAnimation();
}
}