Cómo poner vistas en la parte superior de un ImageView, en relación con el tamaño del contenido de ImageView?
Fondo
Supongamos que quiero mostrar una imagen de algo usando un ImageView, y quiero poner nuevas vistas encima de ella (ImageViews animadas que muestran los pins en una imagen de mapa mundial, por ejemplo, o una vista de Switch en la parte superior de una imagen de smartphone ).
Esto significa que no importa cómo el ImageView muestre la imagen, las vistas deben estar en ella, dentro del punto correcto, con el mismo tamaño especificado, o en un tamaño relacionado con el imageView mismo
- Android ¿Arrastrar y soltar imágenes en la pantalla?
- Escala de ImageView al ancho del dispositivo
- Android 4.0 ImageView setImageBitmap no funciona
- Cómo agregar una sombra y un borde en circular imageView android?
- Cómo obtener el nombre de la imagen en java?
El problema
A diferencia de otras vistas, ImageView puede tener un cierto tamaño, pero su contenido es otra cosa (para mantener la relación de aspecto).
Lo que intenté
He intentado usar ConstraintLayout, pero esto realmente no puede ayudar, porque el ImageView puede cambiar su tamaño (por ejemplo al cambiar la orientación), y por lo tanto arruinar la posición que he dado las vistas en comparación con el ImageView.
He encontrado algunas bibliotecas que pueden manejar una cosa similar (como aquí ) e incluso he hecho una pregunta similar antes ( aquí ), pero todas esas soluciones son para una imagen estática dentro de ImageView, pero lo que busco es agregar una vista En la parte superior de un ImageView.
La pregunta
¿Cómo pongo las vistas en la parte superior del contenido de ImageView correctamente?
¿Cómo puedo escalar las vistas hacia abajo / arriba en comparación con el tamaño del contenido de ImageView?
¿Se puede utilizar ConstraintLayout para cambiar la escala de las vistas según el tamaño de ImageView?
- Establecer vista de imagen después del cambio de orientación
- ¿Por qué el Ancho / Altura del dibujable en ImageView equivocado?
- Problemas de margen de pantalla de inicio?
- Cómo obtener la imagen de sdcard en android?
- Cómo cargar el búfer RGB565 en ImageView
- Cómo encontrar la intersección entre dos ImageView cuando arrastrar y soltar?
- Bitmap demasiado grande para ser cargado en una textura en algunos teléfonos
- Cómo borrar ImageView correctamente?
Hacer FrameLayout
con wrap_content
alrededor de ImageView
. A continuación, puede establecer SwitchView
en la parte superior de ImageView
. Usted podría alinearlo al centro, lado o esquinas y usar los márgenes para conseguir una cierta posición fina.
Aún no se escala con la imagen, pero se pueden obtener muy buenos resultados. Si eso no le conviene, puede obtener programaticamente la anchura / altura de ImageView
y modificar la posición (o los márgenes) de SwitchView
consecuencia.
Con abajo puede manejar el ancho del interruptor o cualquier otra vista según el ancho de la vista de la imagen
android:layout_alignLeft="@+id/imageView" android:layout_alignRight="@+id/imageView"
<Switch android:id="@+id/swi" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/imageView" android:layout_alignRight="@+id/imageView" /> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/swi" android:src="@drawable/download" />
En Java,
ImageView imgView = (ImageView) findViewById(R.id.imageView); imageView.setBackgroundResource(R.drawable.yourDrawable); int width = imgView.getDrawable().getIntrinsicWidth(); Switch switchKey = (Switch) findViewById(R.id.switchKey); switchKey.setMinimumWidth(width);
Y en XML, alinearlo con alignLeft y alignRight con ImageView.
En la medida en que lo consigo, necesita el tamaño de la imagen que se muestra dentro de la vista de la imagen y establecer que como el ancho máximo de la vista de interruptor a la derecha?
Necesita Java y XML para esto,
El archivo XML es básicamente como RelativeLayout con la vista apilada según sea necesario.
<RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:src="@drawable/nonet_icon" android:id="@+id/iconView" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <android.support.v7.widget.SwitchCompat android:layout_width="wrap_content" android:visibility="gone" android:layout_centerInParent="true" android:layout_height="wrap_content" android:id="@+id/switchView"/> </RelativeLayout>
Y el código Java obtiene la anchura de la imagen y la establece en SwitchView.
mSwitchCompat.setVisibility(View.VISIBLE); // 20% x 25% of Content in ImageView final float x = mImageView.getDrawable().getIntrinsicWidth()*.2f; final float y = mImageView.getDrawable().getIntrinsicHeight()*.25f; // waiting for the view to be drawn mSwitchCompat.post(new Runnable() { @Override public void run() { // scale current view Wrt x and y values mSwitchCompat.setScaleX((float)mSwitchCompat.getWidth()/x); mSwitchCompat.setScaleY((float)mSwitchCompat.getHeight()/y); } }); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT); // 30% x 35% of content, for location int xMargin = Math.round(mImageView.getDrawable().getIntrinsicWidth()*.3f); int yMargin = Math.round(mImageView.getDrawable().getIntrinsicHeight()*.35f); // set margin values, can optionally add for top and bottom layoutParams.setMargins(xMargin,0,yMargin,0); mSwitchCompat.setLayoutParams(layoutParams);
Ref: Cómo mostrar el tamaño de imagen de un ImageView Tratando de obtener el tamaño de visualización de una imagen en un ImageView
Ref: Valores dinámicos del tamaño
Haga un comentario si necesita una explicación detallada.
Ejemplo: ¡ Compruebe esta imagen!
Vista escalada en la imagen: Vista escalada en la imagen!
Puede utilizar MarginLayoutParams
con Disposición relativa para establecer la posición izquierda y superior en ImageView
.
image = (ImageView) findViewById(R.id.imageID); MarginLayoutParams marginParams = new MarginLayoutParams(image.getLayoutParams()); marginParams.setMargins(left_margin, top_margin, right_margin, bottom_margin); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams); image.setLayoutParams(layoutParams);
Encontrar información completa para esto en el siguiente enlace:
MarginLayoutParams
Pruebe esto, puede ser que le ayudará.
<RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <ImageView android:id="@+id/img_background" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="centerCrop"/> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/semi_transparent" android:layout_margin="@dimen/spacing_small" android:layout_alignTop="@+id/img_background" android:layout_alignBottom="@id/img_background"> //this layout will expand according to your image size </RelativeLayout> </RelativeLayout>
¿Quieres mostrar el interruptor que se encuentra en la vista de la imagen?
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/ll_download" android:layout_width="100dp" android:layout_height="60dp" android:layout_centerInParent="true" android:orientation="vertical"> <ImageView android:src="@android:drawable/btn_star_big_on" android:layout_width="match_parent" android:layout_height="match_parent" /> <Switch android:id="@+id/mySwitch" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Switch" /> </RelativeLayout>