Search code examples
androidandroid-layoutandroid-xmlrotateanimation

Android rotate xml without any resizing


I have an activity and this is its layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="@drawable/main_background" >

</RelativeLayout>

main_background is a rotate xml. There are two main_background xml for each orientation

drawable-hdpi/main_background.xml :

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android" 
    android:drawable="@drawable/sss" >
</rotate>

drawable-land-hdpi/main_background.xml :

<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android" 
    android:fromDegrees="90"
    android:toDegrees="90"
    android:drawable="@drawable/sss" >
</rotate>

So I want to use the same .jpg file but different rotation for horizontal and vertical orientation. For example, When orientation changes to horizontal , I want to rotate drawable 90 degrees. But here is my results :

Vertical orientation (There is no problem with this):

Vertical orientation

Horizontal orientation (which is my problem):

Horizontal orientation

What i want (without any resizing):

What i want

How can i do that ?


Solution

  • afaik you cannot do that in xml, the only way is to create a custom class extending Drawable that would react on orientarion changes for example:

    class D extends Drawable {
        private Bitmap mBitmap;
        private Matrix mMatrix;
        private boolean mIsLandscape;
    
        public D(Resources res, Bitmap b) {
            mBitmap = b;
            mMatrix = new Matrix();
            mIsLandscape = res.getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
        }
    
        @Override
        protected void onBoundsChange(Rect bounds) {
            RectF src = new RectF(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
            RectF dst = new RectF();
            if (!mIsLandscape) {
                dst.set(0, 0, bounds.width(), bounds.height());
            } else {
                dst.set(0, 0, bounds.height(), bounds.width());
            }
            mMatrix.setRectToRect(src, dst, ScaleToFit.FILL);
            if (mIsLandscape) {
                mMatrix.postRotate(-90);
                mMatrix.postTranslate(0, bounds.height());
            }
        }
    
        @Override
        public void draw(Canvas canvas) {
            canvas.drawBitmap(mBitmap, mMatrix, null);
        }
    
        @Override
        public void setAlpha(int alpha) {
        }
    
        @Override
        public void setColorFilter(ColorFilter cf) {
        }
    
        @Override
        public int getOpacity() {
            return PixelFormat.TRANSLUCENT;
        }
    }