0

I have a floor plan which is centred in an ImageView. The aspect ratio of the image is preserved so there is some space on either side of the image (indicated in red colour).

How can I determine the width of this red space in pixels or dp?

enter image description here

<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"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MyActivity"
    android:background="@color/red"
    android:orientation="vertical">

<ImageView
    android:id="@+id/floor_plan"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/floor_plan2"
    android:adjustViewBounds="true"
    android:layout_toStartOf="@+id/locateMe"
    android:layout_alignParentTop="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentEnd="true"
    />

I note that the margins have been set to 0dp in the dimens.xml file.

Osborne Cox
  • 466
  • 2
  • 7
  • 19

1 Answers1

0

That's only math :

int originalImgWidth  = bitmap.getWidth();
int originalImgHeight  = bitmap.getHeight();

float scale = screenHeight * 1f / originalImgHeight;  
// since your img will fill the screen vertically

float marginSize =  (screenWidth - (originalImgWidth * scale)) /2; 

Note that the size might be negative if the image is bigger than the screen horizontally ^^

see how to get the bitmap here

see how to get screen size here

Community
  • 1
  • 1
Guian
  • 4,563
  • 4
  • 34
  • 54
  • If I just wanted the width of each red section and not the area, could I just use: marginSize = (screenWidth - originalImageWidth) / 2 ? – Osborne Cox Aug 03 '14 at 03:17
  • in my example the 'marginSize' is the width of each red section. (just a note for futur readers) – Guian Aug 05 '14 at 08:12