Android: Obróć obraz w imageview o kąt

Używam poniższego kodu, aby obrócić obraz w ImageView o kąt. Czy istnieje jakaś prostsza i mniej złożona metoda dostępna.

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);
Author: Ironman, 2012-01-24

18 answers

Kolejny prosty sposób na obrócenie ImageView:
UPDATE:
Wymagany import:

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

Kod: (zakładając imageView, angle, pivotX & pivotY są już zdefiniowane)

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

Ta metoda nie wymaga tworzenia nowej bitmapy za każdym razem.

Uwaga: aby obrócić ImageView na ontouch w czasie wykonywania można Ustaw onTouchListener na ImageView i obróć go dodając dwa ostatnie lines (tj. postRotate matrix & set it on imageView ) w powyższym kodzie sekcja w Twoim słuchaczu dotyku ACTION_MOVE część.

 180
Author: Aks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-18 10:56:06

mImageView.setRotation(angle) z API > = 11

 145
Author: Frolik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-24 19:39:47

Jeśli obsługujesz API 11 lub wyższe, możesz użyć następującego atrybutu XML:

android:rotation="90"

Może nie wyświetlać się poprawnie w Android Studio XML preview, ale działa zgodnie z oczekiwaniami.

 54
Author: Oleksiy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-03 18:10:45

Są dwa sposoby, aby to zrobić:

1 Użycie Matrix do utworzenia nowej bitmapy:

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 Użyj RotateAnimation na View, aby obrócić i upewnij się, że animacja jest ustawiona na fillAfter=true, duration=0, i 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"
/>

I nadmuchać animację kodem:

Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotation);
myView.startAnimation(rotation);
 42
Author: Rotemmiz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-25 00:56:07

Wiem, że jest to szalenie późno, ale to było pomocne dla mnie, więc może pomóc innym.

Począwszy od API 11, możesz programowo ustawić bezwzględny obrót ImageView za pomocą metody imageView.setRotation(angleInDegrees);.

Przez absolute, mam na myśli, że można wielokrotnie wywoływać tę funkcję bez konieczności śledzenia bieżącego obrotu. Oznacza to, że jeśli obrócę przez przejście 15F do metody setRotation(), a następnie ponownie wywołam setRotation() z 30F, Obrót obrazu będzie wynosił 30 stopni, a nie 45 stopni.

Uwaga: to działa dla każdej podklasy obiektu View , nie tylko ImageView.

 7
Author: thomaspsk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-25 16:14:26

To jest moja implementacja RotatableImageView . Użycie jest bardzo proste: wystarczy skopiować attrs.XML i RotatableImageView.java do twojego projektu i dodaj RotatableImageView do układu. Ustaw żądany kąt obrotu za pomocą parametru przykład: kąt .

<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>

Jeśli masz problemy z wyświetlaniem obrazu, spróbuj zmienić kod w RotatableImageView.metoda onDraw () lub zamiast tego użyj metody draw ().

 5
Author: petrnohejl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-24 16:38:01

Spróbuj tego na niestandardowym widoku

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
Author: jeet.chanchawat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-21 11:04:01

Oto dobre rozwiązanie dla umieszczenia obróconego rysunku dla 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;
}

Użycie:

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

Inna alternatywa:

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();
        }
    };
}

Również, jeśli chcesz obrócić bitmapę, ale boisz się OOM, możesz użyć rozwiązania NDK, które zrobiłem proszę.

 1
Author: android developer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:36

Po prostu napisz to w swoim onactivityResult

            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
Author: Entertainment world,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-09 04:05:26

Mam na to rozwiązanie. W rzeczywistości jest to rozwiązanie problemu, który pojawia się po rotacji (prostokątny obraz nie pasuje do ImagView) ale to też pokrywa twój problem.. Chociaż To rozwiązanie ma animację na dobre i na złe

    int h,w;
    Boolean safe=true;

Uzyskanie parametrów imageView nie jest możliwe przy inicjalizacji aktywności Aby to zrobić, zapoznaj się z tym rozwiązaniem lub Ustaw wymiary po kliknięciu przycisku w ten sposób

    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 
       }

I kod, który ma być Uruchom, gdy chcemy obrócić 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();
        }
    });

To rozwiązanie jest wystarczające dla powyższego problemu.Chociaż zmniejszy obraz nawet jeśli nie jest to konieczne(gdy wysokość jest mniejsza niż szerokość).Jeśli ci to przeszkadza, możesz dodać inny operator trójkowy wewnątrz scaleX/scaleY.

 1
Author: Gaurav Chaudhari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-25 18:33:23

Myślę, że najlepsza metoda:)

int angle = 0;
imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            angle = angle + 90;
            imageView.setRotation(angle);
        }
    });
 1
Author: Trk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-29 11:57:12

Niestety, nie wydaje mi się. Klasa Matrix jest odpowiedzialna za wszystkie manipulacje obrazami, czy to obracanie, kurczenie/rośnięcie, przekrzywianie itp.

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

Przepraszam, ale nie mogę wymyślić alternatywy. Może ktoś inny może być w stanie, ale kiedy musiałem manipulować obrazem, używałem matrycy. Powodzenia!
 0
Author: roboguy12,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-25 00:18:21

Innym możliwym rozwiązaniem jest stworzenie własnego, niestandardowego widoku obrazu (powiedzmy RotateableImageView extends ImageView)...i nadpisać onDraw (), aby obrócić płótno/bitmapy przed ponownym załadowaniem na płótno.Nie zapomnij przywrócić płótna.

Ale jeśli masz zamiar obrócić tylko jedną instancję widoku obrazu, Twoje rozwiązanie powinno być wystarczająco dobre.

 0
Author: Navin Ilavarasan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-25 00:27:10

Bez matrycy i animacji:

{
    img_view = (ImageView) findViewById(R.id.imageView);
    rotate = new RotateAnimation(0 ,300);
    rotate.setDuration(500);
    img_view.startAnimation(rotate);
}
 0
Author: user4747884,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-09 22:31:33

Spróbuj ten kod w 100% działa;

Na przycisku rotate kliknij Zapisz ten kod:

        @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
Author: Gaurav Sharma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-21 07:57:25

Jeśli chcesz tylko wizualnie obrócić widok, możesz użyć:

iv.setRotation(float)
 0
Author: mgm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-08 15:42:01

Zamiast konwertować obraz na bitmapę, a następnie go obrócić, spróbuj obrócić bezpośredni widok obrazu, jak poniżej.

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
Author: SWAPDROiD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-22 11:51:18

Postępuj zgodnie z poniższą odpowiedzią dla ciągłego obracania imageview

int i=0;

If rotate button clicked

imageView.setRotation(i+90);
i=i+90;
 0
Author: Harish Reddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-12 05:05:35