Android: rotation de l'image dans imageview par un angle

j'utilise le code suivant pour faire tourner une image dans ImageView d'un angle. Existe-t-il une méthode plus simple et moins complexe disponible?

ImageView iv = (ImageView)findViewById(imageviewid);
TextView tv = (TextView)findViewById(txtViewsid);
Matrix mat = new Matrix();
Bitmap bMap = BitmapFactory.decodeResource(getResources(),imageid);
mat.postRotate(Integer.parseInt(degree));===>angle to be rotated
Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0,bMap.getWidth(),bMap.getHeight(), mat, true);
iv.setImageBitmap(bMapRotate);
126
demandé sur Ironman 2012-01-24 08:00:00

18 réponses

une autre façon simple de tourner un ImageView :

mise à jour:

Importations requises:

import android.graphics.Matrix;
import android.widget.ImageView;
Code

: (en supposant imageView , angle , pivotX & pivotY sont déjà définis)

Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX);   //required
matrix.postRotate((float) angle, pivotX, pivotY);
imageView.setImageMatrix(matrix);

cette méthode ne nécessite pas la création d'un nouveau bitmap à chaque fois.

NOTE: pour tourner un ImageView sur ontouch à l'exécution, vous pouvez mettre onTouchListener sur ImageView et tourner en ajoutant les deux derniers lignes (i.e. posttrotate matrix & set it on imageView ) dans le code ci-dessus section dans votre toucher l'auditeur ACTION_MOVE .

180
répondu Aks 2015-08-18 10:56:06

mImageView.setRotation(angle) avec API>=11

145
répondu Frolik 2013-01-24 19:39:47

si vous supportez API 11 ou plus, vous pouvez simplement utiliser L'attribut XML suivant:

android:rotation="90"

il se peut qu'il ne s'affiche pas correctement dans la prévisualisation XML D'Android Studio, mais il fonctionne comme prévu.

54
répondu Oleksiy 2015-04-03 18:10:45

il y a deux façons de faire cela:

1 en utilisant Matrix pour créer un nouveau bitmap:

imageView = (ImageView) findViewById(R.id.imageView);
Bitmap myImg = BitmapFactory.decodeResource(getResources(), R.drawable.image);

Matrix matrix = new Matrix();
matrix.postRotate(30);

Bitmap rotated = Bitmap.createBitmap(myImg, 0, 0, myImg.getWidth(), myImg.getHeight(),
        matrix, true);

imageView.setImageBitmap(rotated);

2 Utilisez RotateAnimation sur le View vous voulez tourner, et assurez-vous que l'Animation définie à fillAfter=true , duration=0 , et fromDegrees=toDgrees

 <?xml version="1.0" encoding="utf-8"?>
<rotate
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:fromDegrees="45"
  android:toDegrees="45"
  android:pivotX="50%"
  android:pivotY="50%"
  android:duration="0"
  android:startOffset="0"
/>

et gonfler l'Animation en code:

Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotation);
myView.startAnimation(rotation);
42
répondu Rotemmiz 2012-01-25 00:56:07

je sais que c'est follement en retard, mais ça m'a été utile pour que ça puisse aider les autres.

à partir de L'API 11, Vous pouvez définir la rotation absolue d'un ImageView de façon programmatique en utilisant la méthode imageView.setRotation(angleInDegrees); .

par absolu, je veux dire que vous pouvez appeler cette fonction à plusieurs reprises sans avoir à garder une trace de la rotation actuelle. Ce qui signifie, Si je tourne en passant 15F à la méthode setRotation() , puis appeler setRotation() à nouveau avec 30F , la rotation de l'image avec be 30 degrés, pas 45 degrés.

Note: cela fonctionne en fait pour n'importe quelle sous-classe de l'objet View , pas seulement ImageView.

7
répondu thomaspsk 2016-10-25 16:14:26

C'est mon implementation of RotatableImageView . L'utilisation est très facile: il suffit de copier attrs.xml et .java dans votre projet et ajouter RotatableImageView à votre mise en page. Régler l'angle de rotation désiré en utilisant le paramètre exemple:angle .

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:example="http://schemas.android.com/apk/res/com.example"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.example.views.RotatableImageView
        android:id="@+id/layout_example_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:scaleType="fitCenter"
        android:src="@drawable/ic_layout_arrow"
        example:angle="180" />
</FrameLayout>

si vous avez des problèmes avec l'affichage de l'image, essayez de changer le code dans RotatableImageView.méthode onDraw () ou utilisez plutôt la méthode draw ().

5
répondu petrnohejl 2012-09-24 16:38:01

essayez ceci sur une vue personnalisée

public class DrawView extends View {


    public DrawView(Context context,AttributeSet attributeSet){
        super(context, attributeSet);
    }

    @Override
    public void onDraw(Canvas canvas) {
        /*Canvas c=new Canvas(BitmapFactory.decodeResource(getResources(), R.drawable.new_minute1)    );

        c.rotate(45);*/

        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.new_minute1), 0, 0, null);
        canvas.rotate(45);
    }
}

1
répondu jeet.chanchawat 2012-12-21 11:04:01

voici une bonne solution pour mettre un dessinateur tournant pour un imageView:

Drawable getRotateDrawable(final Bitmap b, final float angle) {
    final BitmapDrawable drawable = new BitmapDrawable(getResources(), b) {
        @Override
        public void draw(final Canvas canvas) {
            canvas.save();
            canvas.rotate(angle, b.getWidth() / 2, b.getHeight() / 2);
            super.draw(canvas);
            canvas.restore();
        }
    };
    return drawable;
}

utilisation:

Bitmap b=...
float angle=...
final Drawable rotatedDrawable = getRotateDrawable(b,angle);
root.setImageDrawable(rotatedDrawable);

une autre alternative:

private Drawable getRotateDrawable(final Drawable d, final float angle) {
    final Drawable[] arD = { d };
    return new LayerDrawable(arD) {
        @Override
        public void draw(final Canvas canvas) {
            canvas.save();
            canvas.rotate(angle, d.getBounds().width() / 2, d.getBounds().height() / 2);
            super.draw(canvas);
            canvas.restore();
        }
    };
}

aussi, si vous souhaitez tourner le bitmap, mais peur de OOM, vous pouvez utiliser une solution NDK j'ai fait ici

1
répondu android developer 2017-05-23 12:10:36

il suffit d'écrire ceci dans votre résultat d'onactivityrésult

            Bitmap yourSelectedImage= BitmapFactory.decodeFile(filePath);
            Matrix mat = new Matrix();
            mat.postRotate((270)); //degree how much you rotate i rotate 270
            Bitmap bMapRotate=Bitmap.createBitmap(yourSelectedImage, 0,0,yourSelectedImage.getWidth(),yourSelectedImage.getHeight(), mat, true);
            image.setImageBitmap(bMapRotate);
            Drawable d=new BitmapDrawable(yourSelectedImage);
            image.setBackground(d); 
1
répondu Entertainment world 2017-02-09 04:05:26

j'ai un solution pour ce. En fait, c'est une solution à un problème qui se pose après la rotation(L'image rectangulaire ne convient pas à ImagView) mais il couvre votre problème.. Bien que cette Solution ait L'Animation pour le meilleur et pour le pire

    int h,w;
    Boolean safe=true;

obtenir les paramètres d'imageView n'est pas possible à l'initialisation de l'activité Pour ce faire s'il vous plaît se référer à cette solution OU jeu de l' dimensions au clic d'un bouton comme celui-ci

    rotateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(imageView.getRotation()/90%2==0){
                h=imageView.getHeight();
                w=imageView.getWidth();

            }
        .
        .//Insert the code Snippet below here 
       }

et le code à exécuter lorsque nous voulons tourner ImageView

if(safe)     
imageView.animate().rotationBy(90).scaleX(imageView.getRotation()/90%2==0?(w*1.0f/h):1).scaleY(imageView.getRotation()/90%2==0?(w*1.0f/h):1).setDuration(2000).setInterpolator(new LinearInterpolator()).setListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                      safe=false;
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                      safe=true;

                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            }).start();
        }
    });

Cette solution est suffisante pour le problème ci-dessus.Bien qu'il rétrécit l'imageView même si ce n'est pas nécessaire(lorsque la hauteur est plus petite que la largeur).Si cela vous dérange, vous pouvez ajouter un autre opérateur ternaire à l'intérieur de scaleX/scaleY.

1
répondu Gaurav Chaudhari 2017-12-25 18:33:23

je pense que la meilleure méthode :)

int angle = 0;
imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            angle = angle + 90;
            imageView.setRotation(angle);
        }
    });
1
répondu Trk 2018-08-29 11:57:12

malheureusement, je ne pense pas qu'il y en ait. La classe Matrix est responsable de toutes les manipulations d'image, qu'il s'agisse de rotation, de rétrécissement/croissance, de déformation, etc.

http://developer.android.com/reference/android/graphics/Matrix.html

mes excuses, mais je ne peux pas penser à une alternative. Peut-être que quelqu'un d'autre pourrait le faire, mais les fois où j'ai dû manipuler une image, j'ai utilisé une matrice.

Bonne chance!

0
répondu roboguy12 2012-01-25 00:18:21

une autre solution possible est de créer votre propre vue d'Image personnalisée(dites RotateableImageView extends ImageView )...et outrepasser l'onDraw () pour tourner soit la toile/bitmaps avant de se pencher sur la toile.N'oubliez pas de restaurer le dos toile.

mais si vous allez tourner seulement une seule instance de vue d'image,votre solution devrait être assez bonne.

0
répondu Navin Ilavarasan 2012-01-25 00:27:10

sans matrice et animée:

{
    img_view = (ImageView) findViewById(R.id.imageView);
    rotate = new RotateAnimation(0 ,300);
    rotate.setDuration(500);
    img_view.startAnimation(rotate);
}
0
répondu user4747884 2015-04-09 22:31:33

Essayez ce code 100% de travail;

sur le bouton tourner écrire ce code:

        @Override
        public void onClick(View view) {
            if(bitmap==null){
                Toast.makeText(getApplicationContext(), "Image photo is not yet set", Toast.LENGTH_LONG).show();
            }
            else {
                Matrix matrix = new Matrix();
                ivImageProduct.setScaleType(ImageView.ScaleType.MATRIX);   //required
                matrix.postRotate(90,ivImageProduct.getDrawable().getBounds().width()/2,ivImageProduct.getDrawable().getBounds().height()/2);
                Bitmap bmp=Bitmap.createBitmap(bitmap, 0, 0,bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                bitmap.recycle();
                bitmap=bmp;
                ivImageProduct.setImageBitmap(bitmap);
            }
        }
0
répondu Gaurav Sharma 2018-01-21 07:57:25

si vous voulez seulement tourner la vue visuellement, vous pouvez utiliser:

iv.setRotation(float)
0
répondu mgm 2018-02-08 15:42:01

plutôt que de convertir l'image en bitmap et ensuite la tourner essayer de tourner la vue d'image directe comme code ci-dessous.

ImageView myImageView = (ImageView)findViewById(R.id.my_imageview);

AnimationSet animSet = new AnimationSet(true);
animSet.setInterpolator(new DecelerateInterpolator());
animSet.setFillAfter(true);
animSet.setFillEnabled(true);

final RotateAnimation animRotate = new RotateAnimation(0.0f, -90.0f,
    RotateAnimation.RELATIVE_TO_SELF, 0.5f, 
    RotateAnimation.RELATIVE_TO_SELF, 0.5f);

animRotate.setDuration(1500);
animRotate.setFillAfter(true);
animSet.addAnimation(animRotate);

myImageView.startAnimation(animSet);
0
répondu SWAPDROiD 2018-05-22 11:51:18

suivez la réponse ci-dessous pour la rotation continue d'un imageview

int i=0;

si le bouton tourner a cliqué

imageView.setRotation(i+90);
i=i+90;
0
répondu Harish Reddy 2018-08-12 05:05:35