Android:通过角度旋转ImageView中的图像

190

我正在使用以下代码旋转ImageView中的图像角度。 是否有更简单和不那么复杂的方法可用。

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

6
对于2014年的PS版本,在Android Studio中,似乎可以直接在XML中设置“rotation”属性。(如果你不想使用“Text”布局,甚至可以直接点击右侧的“高级属性”按钮!) - Fattie
在这里找到答案。 - Geet Thakur
28个回答

0

试试这段代码,百分百有效;

在旋转按钮点击事件中写入以下代码:

        @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

没有矩阵和动画:

{
    img_view = (ImageView) findViewById(R.id.imageView);
    rotate = new RotateAnimation(0 ,300);
    rotate.setDuration(500);
    img_view.startAnimation(rotate);
}

0

按照下面的答案进行ImageView的连续旋转

int i=0;

如果旋转按钮被点击
imageView.setRotation(i+90);
i=i+90;

0
另一种可能的解决方案是创建自己的自定义图像视图(比如 RotateableImageView extends ImageView ),并重写 onDraw() 方法,在渲染到画布之前旋转画布/位图。别忘了在操作完成后恢复画布。
但如果你只需要旋转单个图像视图实例,你的解决方案应该已经足够好了。

0

不要将图像转换为位图,然后旋转它,尝试像下面的代码一样直接旋转图像视图。

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

只需在您的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); 

0
Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate((float) 20, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);
imageView.setImageMatrix(matrix);

如何使用?

public class MainActivity extends AppCompatActivity {
   int view = R.layout.activity_main;
   TextView textChanger;
   ImageView imageView;
   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(view);
      textChanger = findViewById(R.id.textChanger);
      imageView=findViewById(R.id.imageView);
      textChanger.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            roateImage(imageView);
         }
      });
   }
   private void roateImage(ImageView imageView) {
      Matrix matrix = new Matrix();
      imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
      matrix.postRotate((float) 20, imageView.getDrawable().getBounds().width()/2,    imageView.getDrawable().getBounds().height()/2);
      imageView.setImageMatrix(matrix);
   }
}

0
我添加了几个解决方案。如果你想要在点击按钮时旋转图像,并且图像大小必须填充父布局,你也可以使用https://github.com/rongi/rotate-layouthttps://stackoverflow.com/a/47970311/9139265这段代码也可以工作。
        ImageView photoView = findViewById(R.id.photo_view);
        ImageView rotateBtn = findViewById(R.id.rotate_image);
        FrameLayout photoFrame = dialogView.findViewById(R.id.photoFrame);

        final float[] currentRotation = {0f};
        final boolean[] isFirst = {true};
        final boolean[] isInitial = {true};
        final float[] firstWidth = {0};
        final float[] firstHeight = {0};
        final float[] secondWidth = {0};
        final float[] secondHeight = {0};

        rotate_image.setOnClickListener(view -> {
            if (isInitial[0]) {
                isInitial[0] = false;

                firstWidth[0] = photoView.getWidth();
                firstHeight[0] = photoView.getHeight();

                float frameWidth = photoFrame.getWidth();
                float frameHeight = photoFrame.getHeight();

                if (firstHeight[0] >= firstWidth[0]) {
                    float imageRatio = firstHeight[0] / firstWidth[0];
                    if (frameHeight > frameWidth) {
                        secondWidth[0] = frameWidth;
                        secondHeight[0] = secondWidth[0] / imageRatio;
                    } else {
                        secondHeight[0] = frameHeight;
                        secondWidth[0] = secondHeight[0] * imageRatio;
                    }
                } else {
                    float imageRatio = firstWidth[0] / firstHeight[0];
                    float frameRatio = frameHeight / frameWidth;
                    if (imageRatio >= frameRatio) {
                        secondHeight[0] = frameHeight;
                        secondWidth[0] = secondHeight[0] / imageRatio;
                    } else {
                        secondWidth[0] = frameWidth;
                        secondHeight[0] = secondWidth[0] * imageRatio;
                    }
                }
            }

            float imageWidth = isFirst[0] ? secondWidth[0] : firstHeight[0];
            float imageHeight = isFirst[0] ? secondHeight[0] : firstWidth[0];
            
            isFirst[0] = !isFirst[0];
        // You can use custom animation
        //Animation rotateAnimation = new RotateAnimation(currentRotation, 
        //currentRotation -= 90, Animation.RELATIVE_TO_SELF, 0.5f, 
        //Animation.RELATIVE_TO_SELF, 0.5f);
        //rotateAnimation.setDuration(100);
        //rotateAnimation.setFillAfter(true);
        //photoView.startAnimation(rotateAnimation);

            photoView.animate().rotation(currentRotation[0] -= 90).start();
            photoView.getLayoutParams().height = (int) imageWidth;
            photoView.getLayoutParams().width = (int) imageHeight;
            photoView.requestLayout();
        });

我的xml代码如下:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  <FrameLayout
      android:id="@+id/photoFrame"
      android:layout_width="match_parent"
      android:layout_height="0dp"
      android:layout_marginVertical="10dp"
      app:layout_constraintBottom_toTopOf="@+id/rotate_image"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent" >

      <ImageView
          android:id="@+id/photo_view"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_gravity="center"
          android:adjustViewBounds="true"
          android:scaleType="fitCenter"
          android:src="@mipmap/ic_client_photo_nophoto" />
  </FrameLayout>

    <ImageView
        android:id="@+id/rotate_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/rotate_image"
        android:layout_marginBottom="10dp"

        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

我另外提供了一个没有动画的解决方案,并且它可以使用图像文件正常工作。
    ImageView photoView = findViewById(R.id.photo_view);
    ImageView rotate_image = findViewById(R.id.rotate_image);

    Glide.with(context)
            .load(file)
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .skipMemoryCache(true)
            .into(photoView);
    
    rotate_image.setOnClickListener(view -> {
        rotateImageFile(file.getPath());
        Glide.with(context)
                .load(file)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(photoView);

    });

public void rotateImageFile(String imagePath) {
    try {
        ExifInterface exif = new ExifInterface(imagePath);
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

        switch (orientation) {
            case 1:
                exif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(ExifInterface.ORIENTATION_ROTATE_90));
                break;
            case 6:
                exif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(ExifInterface.ORIENTATION_ROTATE_180));
                break;
            case 3:
                exif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(ExifInterface.ORIENTATION_ROTATE_270));
                break;
            case 8:
                exif.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(ExifInterface.ORIENTATION_NORMAL));
                break;
        }
        exif.saveAttributes();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

另一种解决方案使用位图,但没有动画效果,质量可能会降低,旋转可能不够流畅,请进行测试。
ImageView photoView = findViewById(R.id.photo_view);
ImageView rotate_image = findViewById(R.id.rotate_image);
final Bitmap[] bitmap = {BitmapFactory.decodeFile(file.getPath())};
//If you dont use file add this code inside of setOnClickListener
//bitmap[0] =((BitmapDrawable) photoView.getDrawable()).getBitmap();

    rotate_image.setOnClickListener(view -> {
    //bitmap[0] =((BitmapDrawable) photoView.getDrawable()).getBitmap();
    Matrix matrix = new Matrix();
    matrix.postRotate(90);
    bitmap[0] = Bitmap.createBitmap(bitmap[0], 0, 0, bitmap[0].getWidth(), bitmap[0].getHeight(), matrix, true);
    photoView.setImageBitmap(bitmap[0]);
});

我在上面添加了链接地址,这是示例代码:
    ImageView photoView = findViewById(R.id.photo_view);
    ImageView rotate_image = findViewById(R.id.rotate_image);

        rotate_image.setOnClickListener(view -> {
        float scale = photoView.getRotation() % 180 == 0 ? (float) photoView.getWidth() / photoView.getHeight() : 1.0f;
        photoView.animate().rotationBy(90).scaleX(scale).scaleY(scale).setDuration(100).start();
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接