Shirish Herwade
Shirish Herwade

Reputation: 11711

android what should be pivot point to rotate image around its center of base

Please read the whole question carefully before marking duplicate or closing it

I want to rotate a image(specifically arrow image) around its center point of base.

e.g. At start my image will be like second hand in a clock on 9. And suppose if I rotate that image by 30 degree, it should look like clock second hand on 10 and if 120 degree the clock second hand on 1.

So I want to rotate that image around it's center(along x axis) of base.

So what should I pass as pivot(X & Y) if I first code

imageView.setPivotX(1f);
            imageView.setPivotY(1f);
            imageView.setRotation(-30);

or second code

Matrix matrix = new Matrix();
    imageView.setScaleType(ScaleType.MATRIX);
    matrix.postRotate((float) 20, 0f, 0f);
    imageView.setImageMatrix(matrix);

or third code

Bitmap myImg = BitmapFactory.decodeResource(getResources(), R.drawable.arrow_0_degree);
    Matrix matrix = new Matrix();
    matrix.postRotate(30);
    Bitmap rotated = Bitmap.createBitmap(myImg, 0, 1, myImg.getWidth(), myImg.getHeight(), matrix, true);
    imageView.setImageBitmap(rotated);

or fourth code

final RotateAnimation rotateAnim = new RotateAnimation(0.0f, degree,
        RotateAnimation.RELATIVE_TO_SELF, 0.5f,
        RotateAnimation.RELATIVE_TO_SELF, 0.5f);

rotateAnim.setDuration(0);
rotateAnim.setFillAfter(true);
imgview.startAnimation(rotateAnim);

Added an image for better understanding which rotated in 90 degrees along clockwise.

And I hope in future google will add more and clear documentation about the pivot points.

Thanks in advance.enter image description here

Upvotes: 6

Views: 7760

Answers (2)

Mudit Goel
Mudit Goel

Reputation: 354

You can simply rotate the arrow by setting the pivotX as arrow width and pivotY as arrow height/2 and then set rotation. Refer below code :

            <ImageView
                android:id="@+id/imgVwArrow"
                android:layout_width="128dp"
                android:layout_height="36dp"
                android:transformPivotX="128dp"
                android:transformPivotY="18dp"
                android:src="@mipmap/ic_arrow" />

Here the width is 128dp and so is pivotX and height is 36dp while pivotY is 18dp. Now you can set rotation either directly in xml or programmatically using the following code :

imgVwArrow.rotation = 30f

Upvotes: 0

koni
koni

Reputation: 1795

You were almost right with the fourth code ^^

You can achieve this like that :

    final RotateAnimation rotateAnim = new RotateAnimation(0.0f, 30,
            RotateAnimation.RELATIVE_TO_SELF, 0.5f,
            RotateAnimation.RELATIVE_TO_SELF, 1f);
    rotateAnim.setDuration(0);
    rotateAnim.setFillAfter(true);
    mImageView.setAnimation(rotateAnim);
    rotateAnim.start();

Upvotes: 12

Related Questions