在onTouchEvent()时间里面加了一个scale 缩放动画效果,效果和预期不同

//设置动画属性 
  animation = new ScaleAnimation(1.0f, 0.5f, 1.0f, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f,Animation.RELATIVE_TO_SELF, 0.5f);
    animation.setDuration(500);// 设置动画持续时间
    animation.setRepeatCount(1);// 设置重复次数
    animation.setRepeatMode(Animation.REVERSE);


    //onTouchEvent()事件
    public boolean onTouchEvent(MotionEvent event) {
    switch (event.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            int width = iv.getWidth();
            int height = iv.getHeight();
            iv.setX(event.getX() - (width/2) );//iv是图片所在的imageView控件
            iv.setY(event.getY() - (height/2) );
            iv.startAnimation(animation);
            break;
        }
    return true;
}


就是想实现一个类似相机手动点击聚焦的动画效果,但是实际效果是在点击屏幕后动画位置能确定,但是缩放中心是变化的,并不是设置的图片的中心点,请有经验的人帮忙指出问题,多谢!

因为你做动画前突然setX值等,中心不好确定了。换用ObjectAnimation或ValueAnimation吧,自己实现缩放机制
ValueAnimator valueAnimator = ValueAnimator.ofFloat(1, 0.5f);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float v = (Float) animation.getAnimatedValue();
ball.setScaleX(v);
ball.setScaleY(v);
}
});
valueAnimator.setDuration(500);// 设置动画持续时间
valueAnimator.setRepeatCount(1);// 设置重复次数
valueAnimator.setRepeatMode(Animation.REVERSE);
@Override
public boolean onTouch(MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
int width = ball.getWidth();
int height = ball.getHeight();
ball.setX(event.getX() - (width / 2));//ball是图片所在的imageView控件
ball.setY(event.getY() - (height / 2));

            ball.setPivotX(ball.getWidth() / 2f);
            ball.setPivotY(ball.getHeight() / 2f);

            valueAnimator.start();
            break;
    }
    return true;
}

这个问题我遇到过,是因为你用错了方法。

MotionEvent里有如下两种方法(对应y轴也一样),一个是getX(),一个是getRawX()。

这两个方法是有区别的。

getX()是指当前你的手指在touch的控件上相对该控件的位置(也就是iv的位置)。当你的手指移动时,你的控件跟着移动,这个时候,你的手指和iv的相对位置又发生了变化,就会发生iv一直跳动的现象

getRawX()是你的手指相对于屏幕的位置,这个原坐标是固定的。一般要实现控件跟随,都是用此方法。