android 代码实现呼吸灯效果
时间: 2023-07-28 18:12:45 浏览: 180
在Android中实现呼吸灯效果,可以通过使用ValueAnimator来实现。具体实现步骤如下:
1. 创建一个View,设置其背景色为需要的颜色。
2. 创建一个ValueAnimator对象,设置动画时长、循环次数、动画插值器等属性。
3. 在ValueAnimator的监听器中,实现对View的背景色进行动态修改,从而实现呼吸灯效果。
以下是示例代码:
```
public class BreathingLightView extends View {
private int mColor;
private Paint mPaint;
private ValueAnimator mAnimator;
private int mAlpha;
public BreathingLightView(Context context) {
this(context, null);
}
public BreathingLightView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public BreathingLightView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mColor = Color.parseColor("#FF4081");
mAnimator = ValueAnimator.ofInt(0, 255);
mAnimator.setDuration(2000);
mAnimator.setRepeatCount(ValueAnimator.INFINITE);
mAnimator.setRepeatMode(ValueAnimator.REVERSE);
mAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mAlpha = (int) animation.getAnimatedValue();
mPaint.setColor(Color.argb(mAlpha, Color.red(mColor), Color.green(mColor), Color.blue(mColor)));
invalidate();
}
});
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
mPaint.setColor(Color.argb(mAlpha, Color.red(mColor), Color.green(mColor), Color.blue(mColor)));
canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2, mPaint);
}
public void startBreathing() {
if (mAnimator != null && !mAnimator.isStarted()) {
mAnimator.start();
}
}
public void stopBreathing() {
if (mAnimator != null && mAnimator.isStarted()) {
mAnimator.end();
}
}
}
```
在Activity中,可以通过以下方式来使用BreathingLightView:
```
public class MainActivity extends AppCompatActivity {
private BreathingLightView mBreathingLightView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBreathingLightView = findViewById(R.id.breathing_light_view);
mBreathingLightView.startBreathing();
}
@Override
protected void onDestroy() {
super.onDestroy();
mBreathingLightView.stopBreathing();
}
}
```
其中,activity_main.xml中的布局代码如下:
```
<com.example.myapplication.BreathingLightView
android:id="@+id/breathing_light_view"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center"
android:background="@android:color/white" />
```
阅读全文