获得焦点时,在一个View / ImageView上实现Android缩放动画?

时间:2013-12-24 03:18:22

标签: android animation view

我希望在获得焦点时为View(或ImageView)实现缩放动画。这是我目前的实施:

public class ScaleFocusImageView extends ImageView {
    private Context mContext;

    public ScaleFocusImageView(Context context, AttributeSet attr) {
        super(context, attr);
        mContext = context;
    }

    @Override
    protected void onFocusChanged (boolean gainFocus, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
        if(gainFocus) {
            Animation a = AnimationUtils.loadAnimation(mContext, R.anim.scale_up);
            this.startAnimation(a);
        }

    }
}

这是我的动画xml'cale_up.xml':

<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
    android:fromXScale="1.0"
    android:toXScale="1.5"
    android:fromYScale="1.0"
    android:toYScale="1.5"
    android:pivotX="50%p"
    android:pivotY="50%p"
    android:duration="175"/>
</set>

最终获得焦点时我无法获得比例效果,我只是看到它快速缩放并正常缩小到原始状态。为什么这个实现不符合我的预期,我该如何解决?

2 个答案:

答案 0 :(得分:1)

好的,现在试试这个更新的代码: -

这是imageview的类: -

public class ScaleFocusImageView extends ImageView {
private Context mContext;
boolean flag;

public ScaleFocusImageView(Context context, AttributeSet attr) {
    super(context, attr);
    mContext = context;
}

@Override
protected void onFocusChanged(boolean gainFocus, int direction,
        Rect previouslyFocusedRect) {
    super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
    if (gainFocus) {
        zoom(1f, 1f, new PointF(getWidth() / 2, getHeight() / 2));
    } else {
        zoom(2f, 2f, new PointF(getWidth() / 2, getHeight() / 2));
    }

}

/** zooming is done from here */
@SuppressLint("NewApi")
public void zoom(Float scaleX, Float scaleY, PointF pivot) {
    setPivotX(pivot.x);
    setPivotY(pivot.y);
    setScaleX(scaleX);
    setScaleY(scaleY);
}
 }

答案 1 :(得分:0)

将其添加到您的XML动画中:

    android:repeatMode="reverse"

通过反转动画,图像不会缩小加载,但动画将按照反转比例缩放。

xml动画文件现在将如下所示:

<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
    android:fromXScale="1.0"
    android:toXScale="1.5"
    android:fromYScale="1.0"
    android:toYScale="1.5"
    android:pivotX="50%p"
    android:pivotY="50%p"
    android:duration="3000"
    android:repeatMode="reverse"
    android:repeatCount="infinite"/>