欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

属性动画 自定义view小球从左上角移动到右下角 颜色渐变

程序员文章站 2022-06-04 13:31:00
...

//小球的属性封装一个bean类
public class CirclePoint {
private float positionX;
private float positionY;
private int radius =100;

public float getPositionX() {
    return positionX;
}

public void setPositionX(float positionX) {
    this.positionX = positionX;
}

public float getPositionY() {
    return positionY;
}

public void setPositionY(float positionY) {
    this.positionY = positionY;
}

public int getRadius() {
    return radius;
}

public void setRadius(int radius) {
    this.radius = radius;
}

}
//自定义view
public class CircleView extends View implements View.OnClickListener {
private CirclePoint circleStart;
private Paint paint;
public CircleView(Context context) {
super(context);
}

public CircleView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}
int red = 50;
int green = 100;
int blue = 200;
private void init() {
    circleStart = new CirclePoint();
    paint = new Paint();
    paint.setColor(Color.argb(255,red,green,blue));
    setOnClickListener(this);
}
public void setRed(int red) {
    this.red = red;
}
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    paint.setColor(Color.argb(255, red,green,blue));
    //核心代码
    canvas.drawCircle(circleStart.getPositionX() + 100, circleStart.getPositionY() + 100, circleStart.getRadius(), paint);
}
@Override
public void onClick(View v) {
 startAnimation();
}
private void startAnimation() {
    AnimatorSet animatorSet = new AnimatorSet();
    ObjectAnimator objectAnimatorX = ObjectAnimator.ofFloat(circleStart, "positionX", 100, 500);
    objectAnimatorX.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            invalidate();
        }
    });
    ObjectAnimator objectAnimatorY = ObjectAnimator.ofFloat(circleStart, "positionY", 100, 1000);
    ObjectAnimator objectAnimatorColor = ObjectAnimator.ofInt(this,"red",0,255);
    animatorSet.play(objectAnimatorX).with(objectAnimatorY).with(objectAnimatorColor);
    animatorSet.setDuration(5000);
    animatorSet.start();
}

}

//在xml文件里写布局
<com.yy.myanimat.CircleView
android:id="@+id/circleView"
android:layout_width=“wrap_content”
android:layout_height=“wrap_content” />