VectorDrawable: ¿Cómo posicionarlo sobre lienzo?
Hola para mi vista personalizada:
MyCustomView extends View
Hice un VectorDrawable
- Google Play: necesitas comprobar el icono dentro de tu APK porque no es válido
- ¿Cómo animar un VectorDrawable de una manera fluida-como?
- Coracteres corrompidos o desaparecidos después de ejecutar Proguard
- Herramientas para crear AnimatedVectorDrawable
- Vector dibujable no dibujado correctamente en Android Studio
mMyVectorDrawable = VectorDrawableCompat.create(getContext().getResources(), R.drawable.ic_some_image, null);
He establecido sus límites
mMyVectorDrawable .setBounds(0,0,mMyVectorDrawable .getIntrinsicWidth(),mMyVectorDrawable .getIntrinsicHeight());
Y lo dibujo en la lona
mMyVectorDrawable .draw(canvas);
Veo la imagen en la posición 0,0
Pero ¿cómo lo posiciono? ¿Cómo puedo posicionar el Rect, pensé que los dos primeros params de setBounds
sería coordenadas X e Y de dónde empezar a dibujar, pero esto sólo afecta al tamaño.
¿Cómo puedo posicionar mi vector dibujable sobre un lienzo?
Gracias por leer
- Android Vector Drawable <defs> no es compatible. ¿Como arreglarlo?
- Android Robolectric y elementos decorativos vectoriales
- AppCompat 23.3 ¿Los vectores de ayuda ya no funcionan?
- Android: obtener recursos $ NotFoundException para abc_ic_ab_back_material
- ¿Puedo usar un vector dibujable de la misma manera que usé un parche 9?
- ¿Por qué mi SVG no se carga en Vector Asset Studio
- Cómo preservar la relación de aspecto de VectorDrawable?
- ¿Cómo obtienes un objeto Drawable a través de un TypedArray cuando el recurso drawable es un Vector Drawable?
Puedes traducir tu lienzo antes de dibujar el dibujable en él.
mMyVectorDrawable.setBounds(0, 0, width, height); canvas.translate(dx, dy); mMyVectorDrawable.draw(canvas);
Los valores dx
y dy
especifican el desplazamiento desde las coordenadas (0, 0)
donde se dibujará el siguiente dibujable.
Si lo desea, también puede deshacer la traducción después:
canvas.translate(-dx, -dy);
La pregunta es un poco vieja, pero si puede ayudar a alguien, tengo una respuesta basada en esta .
La idea es obtener el vector dibujable usando:
Drawable drawable = AppCompatDrawableManager.get().getDrawable(context, R.drawable.my_drawable);
Luego obtenemos el Bitmap de este Drawable directamente con el tamaño que queremos mantener la calidad. Entonces, porque tenemos un mapa de bits podemos dibujarlo donde queremos.
Nota: En la sección defaultConfig de su build.gradle, no olvide poner esta línea para retro-compatibilidad:
vectorDrawables.useSupportLibrary = true
Aquí está el código para obtener el mapa de bits de la Drawable:
/** * Extract the Bitmap from a Drawable and resize it to the expectedSize conserving the ratio. * * @param drawable Drawable used to extract the Bitmap. Can be null. * @param expectSize Expected size for the Bitmap. Use {@link #DEFAULT_DRAWABLE_SIZE} to * keep the original {@link Drawable} size. * @return The Bitmap associated to the Drawable or null if the drawable was null. * @see <html><a href="https://stackoverflow.com/a/10600736/1827254">Stackoverflow answer</a></html> */ public static Bitmap getBitmapFromDrawable(@Nullable Drawable drawable, int expectSize) { Bitmap bitmap; if (drawable == null) { return null; } if (drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; if (bitmapDrawable.getBitmap() != null) { return bitmapDrawable.getBitmap(); } } if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) { bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel } else { float ratio = (expectSize != DEFAULT_DRAWABLE_SIZE) ? calculateRatio(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), expectSize) : 1f; int width = (int) (drawable.getIntrinsicWidth() * ratio); int height = (int) (drawable.getIntrinsicHeight() * ratio); bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); } Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } /** * Calculate the ratio to multiply the Bitmap size with, for it to be the maximum size of * "expected". * * @param height Original Bitmap height * @param width Original Bitmap width * @param expected Expected maximum size. * @return If height and with equals 0, 1 is return. Otherwise the ratio is returned. * The ration is base on the greatest side so the image will always be the maximum size. */ public static float calculateRatio(int height, int width, int expected) { if (height == 0 && width == 0) { return 1f; } return (height > width) ? expected / (float) width : expected / (float) height; }
- Cómo mostrar FragmentBreadCrumbs en una aplicación Honeycomb
- ¿Cómo crear un imagebutton de forma irregular donde la parte transparente de la imagen no se puede hacer clic?