android 自定义漂浮,Android漂浮背景效果的制作方法
时间: 2024-02-24 13:55:53 浏览: 81
要实现Android自定义漂浮效果,可以按照以下步骤进行:
1. 创建一个自定义View,在onDraw()方法中绘制漂浮物;
2. 在自定义View中添加一个动画,实现漂浮物的移动效果;
3. 在Activity中将自定义View添加到布局中;
4. 在Activity中启动动画。
下面是一个简单的示例代码,可以实现随机漂浮物的移动效果:
```java
public class DriftingView extends View {
private Paint mPaint;
private int mWidth, mHeight;
private float mX, mY;
private float mRadius;
private int mColor;
public DriftingView(Context context) {
super(context);
init();
}
public DriftingView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public DriftingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.FILL);
mRadius = dp2px(20);
mColor = Color.RED;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setColor(mColor);
canvas.drawCircle(mX, mY, mRadius, mPaint);
}
public void setColor(int color) {
mColor = color;
invalidate();
}
public void setRadius(float radius) {
mRadius = radius;
invalidate();
}
public void startDrift() {
ValueAnimator animator = ValueAnimator.ofFloat(0, 1);
final Random random = new Random();
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = (float) animation.getAnimatedValue();
mX = value * mWidth;
mY = value * mHeight;
mY -= Math.sin(mX / mWidth * Math.PI * 2) * mHeight / 5;
mX += (random.nextFloat() - 0.5) * mWidth / 10;
mY += (random.nextFloat() - 0.5) * mHeight / 10;
invalidate();
}
});
animator.setDuration(5000);
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.start();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
mX = mWidth / 2;
mY = mHeight / 2;
}
private float dp2px(float dpValue) {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, getResources().getDisplayMetrics());
}
}
```
在Activity中使用该自定义View,可以通过以下代码启动漂浮动画:
```java
DriftingView driftingView = new DriftingView(this);
driftingView.startDrift();
layout.addView(driftingView);
```
其中,`layout`为Activity中的布局容器。这样就可以实现一个简单的Android自定义漂浮效果了。
阅读全文