Android Canvas 波浪背景
时间: 2024-02-08 08:40:40 浏览: 29
以下是一个简单的 Android Canvas 波浪背景示例:
首先,在 XML 布局文件中创建一个自定义 View:
```
<com.example.WaveBackgroundView
android:id="@+id/wave_background"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
```
然后,在 WaveBackgroundView 类中实现 onDraw 方法:
```
public class WaveBackgroundView extends View {
private Paint paint;
private Path path;
private int waveColor = Color.BLUE;
private int waveWidth = 500;
private int waveHeight = 100;
private int waveSpeed = 10;
private int waveOffset = 0;
public WaveBackgroundView(Context context) {
super(context);
init();
}
public WaveBackgroundView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public WaveBackgroundView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.FILL);
path = new Path();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getWidth();
int height = getHeight();
int halfWaveWidth = waveWidth / 2;
path.reset();
path.moveTo(0, height);
for (int x = 0; x <= width + waveWidth; x += waveWidth) {
int y = (int) (waveHeight * Math.sin((x + waveOffset) * 2 * Math.PI / waveWidth));
path.lineTo(x - halfWaveWidth, height - y);
path.lineTo(x, height);
}
path.lineTo(width, height);
path.lineTo(0, height);
path.close();
paint.setColor(waveColor);
canvas.drawPath(path, paint);
waveOffset += waveSpeed;
if (waveOffset >= waveWidth) {
waveOffset -= waveWidth;
}
postInvalidateDelayed(20);
}
}
```
这里定义了一些属性来控制波浪的颜色、宽度、高度、速度和偏移量。在 onDraw 方法中,根据这些属性使用 sin 函数绘制波浪形状,并重复绘制直到覆盖整个 View。然后,更新偏移量并使用 postInvalidateDelayed 方法在 20 毫秒后重绘 View,以创建波浪动画效果。
最后,在 Activity 中找到该 View 并设置属性:
```
WaveBackgroundView waveBackground = findViewById(R.id.wave_background);
waveBackground.setWaveColor(Color.parseColor("#87CEEB"));
waveBackground.setWaveWidth(500);
waveBackground.setWaveHeight(100);
waveBackground.setWaveSpeed(10);
```
这样就可以创建一个波浪背景了。