import com.mytoutou.cehua.ResourceTable;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.*;
import ohos.multimodalinput.event.TouchEvent;
import java.util.Random;
public class MainPageListener implements Component.TouchEventListener {
private DirectionalLayout page;
private float lastY;
private float lastX;
private float currentY;
private float currentX;
private int pointId;
private float distance;
public MainPageListener(DirectionalLayout page) {
this.page = page;
}
@Override
public boolean onTouchEvent(Component component, TouchEvent ev) {
int action = ev.getAction();
switch (action) {
case TouchEvent.PRIMARY_POINT_DOWN:
pointId = ev.getPointerId(ev.getIndex());
lastY = currentY = ev.getPointerPosition(pointId).getY();
lastX = currentX = ev.getPointerPosition(pointId).getX();
//取中心---显示
//创建一个点赞装下love的容器,在里面放一张love图片
DirectionalLayout love = new DirectionalLayout(page.getContext());
love.setWidth(200);
love.setHeight(200);
Image image = new Image(page.getContext());
image.setWidth(200);
image.setHeight(200);
image.setPixelMap(ResourceTable.Media_dz_heart_1);
love.addComponent(image);
StackLayout pageStack = (StackLayout) page.findComponentById(ResourceTable.Id_page_a_stack);
pageStack.addComponent(love);
//随机左右倾斜一个角度--->向倾斜的方向移动并且移动过放大逐渐淡化消失
//爱心所在的位置
love.setContentPosition(lastX, lastY);
//(1)、第一种方式
float v = getRandomRotateValue(-35F, -25F, -0F, 25F, 35F);
//创建一个属性动画
AnimatorProperty animatorProperty = new AnimatorProperty();
//属性动画塞入需要执行的动画内容
animatorProperty.setTarget(love);
animatorProperty.setStateChangedListener(new Animator.StateChangedListener() {
@Override
public void onStart(Animator animator) {
}
@Override
public void onStop(Animator animator) {
}
@Override
public void onCancel(Animator animator) {
}
@Override
public void onEnd(Animator animator) {
//动画结束之后将其移除掉
pageStack.removeComponent(love);
}
@Override
public void onPause(Animator animator) {
}
@Override
public void onResume(Animator animator) {
}
});
animatorProperty.rotate(v)//每次随机旋转的角度
.setDuration(800)//动画持续800ms(毫秒)
.scaleX(2.5F)//向x轴放大2.5倍
.scaleY(2.5F)//向y轴放大2.5倍
.moveByY(-300)//向上是负值,向下是正值---移动x个像素
.alpha(0)
.start();//这个线性函数---理解渐渐消失
//(1)、第一种方式
break;
case TouchEvent.POINT_MOVE:
currentY = ev.getPointerPosition(pointId).getY();
distance = currentY - lastY;
page.setMarginBottom(page.getMarginBottom() + (int) distance);
break;
case TouchEvent.PRIMARY_POINT_UP:
break;
}
return true;
}
//随机1-5个数的角度
private float getRandomRotateValue(float... rotate) {
Random r = new Random();
int a = r.nextInt(4) + 1;
return randomZF() == 0 ? rotate[a] : -rotate[a];
}
//随机0或1是为了取角度正负数
private float randomZF() {
return new java.util.Random().nextBoolean() ? 1 : 0;
}
}