Search code examples
javaandroidkotlinimageviewandroid-imageview

Android: how to have a cropped image after ImageView rotation?


I have a problem with an ImageView that I rotate in a RelativeLayout. Here is my problem:

enter image description here

How should I do to obtain what I want ?

Thanks !

My java code:

 previewImageView.setRotation(rotAngle);

My xml:

    <RelativeLayout
        android:id="@+id/previewLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <com.xxxx.SquareImageView
            android:id="@+id/previewBackgroundImageView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="fitXY"
            android:src="@drawable/dark_blue_page"
            />

        <com.xxxx.TouchImageView
            android:id="@+id/previewImageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:layout_alignStart="@+id/previewBackgroundImageView"
            android:layout_alignTop="@+id/previewBackgroundImageView"
            android:layout_alignEnd="@+id/previewBackgroundImageView"
            android:layout_alignBottom="@+id/previewBackgroundImageView"

            android:layout_margin="50dp"
            android:scaleType="centerInside"
            />

    </RelativeLayout>

Solution

  • The easiest solution would be to wrap the ImageView in the FrameLayout

    Like that:

     <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="50dp"
        android:layout_alignStart="@+id/previewBackgroundImageView"
        android:layout_alignTop="@+id/previewBackgroundImageView"
        android:layout_alignEnd="@+id/previewBackgroundImageView"
        android:layout_alignBottom="@+id/previewBackgroundImageView"
        android:layout_alignLeft="@+id/previewBackgroundImageView"
        android:layout_alignRight="@+id/previewBackgroundImageView" >
    
         <com.xxxx.TouchImageView
            android:id="@+id/previewImageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:scaleType="centerInside" />
    
     </FrameLayout>
    

    That way the FrameLayout would clip any part of its child views that is beyond the FrameLayout boundaries. That is based on the view attribute android:clipChildren that have a default value of true

    Drawbacks: That brings more layouts nesting to the project that could potentially harm the performance of the application. But that one FrameLayout alone would not do any harm by itself.