I am placing a background image in an Activity obtained from the drawable
folder, this is the code I implemented for that action:
ConstraintLayout constraintLayout = (ConstraintLayout)findViewById(R.id.principal);
// Obtener la imagen desde Drawable
Drawable image = ContextCompat.getDrawable(getApplicationContext(), R.drawable.alert);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
// Colocar la imagen de fondo de pantalla
constraintLayout.setBackground(image);
}
But when you run it in the emulator you see the big image:
What I want is to resize the image so that it is centered and with a width and height programmatically defined something like that.
Any way to resize the image?
EDITING
This is a solution taking into account what is recommended by @Andrespengineer and making use of the class ConstraintSet
in this way I could achieve what was committed maybe not the most viable but at the moment it works.
XML file:
<?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:id="@+id/principal"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="@+id/image"
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" />
</android.support.constraint.ConstraintLayout>
Activity code:
int recurso = getResources().getIdentifier("alert", "drawable", getPackageName());
ImageView imageView = new ImageView(this);
imageView.setId(R.id.image);
imageView.setImageResource(recurso);
ConstraintLayout constraintLayout = findViewById(R.id.principal);
ConstraintLayout.LayoutParams imageConstraint = new ConstraintLayout.LayoutParams(
ConstraintLayout.LayoutParams.MATCH_PARENT,
ConstraintLayout.LayoutParams.MATCH_PARENT);
imageView.setLayoutParams(imageConstraint);
constraintLayout.addView(imageView);
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(constraintLayout);
constraintSet.connect(imageView.getId(), ConstraintSet.TOP, constraintLayout.getId(), ConstraintSet.TOP, 400);
constraintSet.connect(imageView.getId(), ConstraintSet.LEFT, constraintLayout.getId(), ConstraintSet.LEFT, 400);
constraintSet.connect(imageView.getId(), ConstraintSet.RIGHT, constraintLayout.getId(), ConstraintSet.RIGHT, 400);
constraintSet.connect(imageView.getId(), ConstraintSet.BOTTOM, constraintLayout.getId(), ConstraintSet.BOTTOM, 400);
constraintSet.applyTo(constraintLayout);