How do I make the ImageView the same size as the image in pixels

Viewed 101

I have an image that is 242x314 pixels in size, but when I put it in an ImageView, the image becomes 726x942, which I see in the LayoutInspector, the layout_width and layout_height are set to wrap_content, why is that?How can I make the ImageView the same size as the image.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/eight_age" />

</android.support.constraint.ConstraintLayout>
1 Answers

You need to set ImageView from java code after getting the width and height of image. Here is the java code for it.

   public void setImage(String filePath){//If you have a bitmap use it directly
        Bitmap bitmap = BitmapFactory.decodeFile(filePath);
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        ImageView imageView = findViewById(R.id.image);//Change id according you name it in xml
        imageView.setLayoutParams(new ConstraintLayout.LayoutParams(width,height));
    }

And here is the xml code

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">


    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/eight_age" 
        android:id="@+id/image"<!--This line is for id change it according to need-->
        android:scaleType="fitCenter"/><!--Keep this line as is-->

</android.support.constraint.ConstraintLayout>
Related