Search code examples
javaandroidandroid-imageviewimage-rotation

setRotation change the ImageView position


In the code below, I'm trying to replace a sticker with an imageView keeping the same [Width, Height, TranslateX, TranslateY, and Rotation] of the sticker to give it to the imageView :

            transX = selectedSticker.getTransX();
            transY = selectedSticker.getTransY();
            rotation = selectedSticker.getCurrentAngle();
            
            ImageView mHoverView = findViewById(R.id.drawingView);
            mHoverView.setLayoutParams(new FrameLayout.LayoutParams((int) stickerWidth, (int) stickerHeight));
            
            mHoverView.setTranslationX(transX);
            mHoverView.setTranslationY(transY);
            mHoverView.setRotation(rotation);
            mHoverView.setImageResource(R.drawable.dog);
            mHoverView.setBackgroundColor(Color.BLUE);

When I click on REPLACE button to replace the sticker with imageView, everything works just fine, the problem starts when I rotate the sticker and clicks on the REPLACE button, the imageView takes the same rotation as the sticker, but it set in the wrong position (the imageView is not rotated around it center) :

e.g.

NO ROTATION :

WITH ROTATION :


Solution

  • The issue was I didn't set the PivotX and PivotY so the view is not rotated around the center, here's the full code :

    float[] values = new float[9];
    selectedSticker.getMatrix().getValues(values);
    float dx = values[2];
    float dy = values[5];
    mHoverView.setPivotX(0.0f);
    mHoverView.setPivotY(0.0f);
    mHoverView.setTranslationX(dx);
    mHoverView.setTranslationY(dy);
    mHoverView.setRotation(rotation);
    mHoverView.invalidate();