Thursday, February 21, 2019

Flip image like a coin

We want an image move flip like a coin.
Declare two global variable.
boolean quay;
private ObjectAnimator mFlipper;
Import library, copy to below findViewByid.
final Bitmap a = BitmapFactory.decodeResource(getResources(), R.drawable.image);
final Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.image);      
im.setImageBitmap(a);
quay = true;           
mFlipper = ObjectAnimator.ofFloat(im, "rotationX", 0f, 360f);
mFlipper.setDuration(500);
mFlipper.setInterpolator(new LinearInterpolator());
mFlipper.setRepeatCount(Animation.INFINITE);
mFlipper.addUpdateListener(new AnimatorUpdateListener() {
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
@SuppressLint("NewApi")
@Override
public void onAnimationUpdate(ValueAnimator animation) {
if (animation.getAnimatedFraction() >= 0.25f && quay) {
im.setImageBitmap(b);
quay = false;
}
if (animation.getAnimatedFraction() >= 0.75f && !quay) {
im.setImageBitmap(a);
quay = true;
                     }
                 }
             });
Put this line in any button.
mFlipper.start();
If you want it flip when click to image, copy this lines to above last bracket.
@Override
    public boolean onTouchEvent(MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_DOWN) {
            mFlipper.start();
            return true;
        }
        return super.onTouchEvent(event);
    }
If you want it flip some time, edit line mFlipper.setRepeatCount(Animation.INFINITE);
If image has two face, change second bitmap to
final Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.image2);



No comments:

Post a Comment