Android: Rotar la imagen en imageview por un ángulo
Estoy usando el siguiente código para rotar una imagen en ImageView por un ángulo. ¿Hay algún método más simple y menos complejo disponible.
ImageView iv = (ImageView)findViewById(imageviewid);
TextView tv = (TextView)findViewById(txtViewsid);
Matrix mat = new Matrix();
Bitmap bMap = BitmapFactory.decodeResource(getResources(),imageid);
mat.postRotate(Integer.parseInt(degree));===>angle to be rotated
Bitmap bMapRotate = Bitmap.createBitmap(bMap, 0, 0,bMap.getWidth(),bMap.getHeight(), mat, true);
iv.setImageBitmap(bMapRotate);
18 answers
Otra forma sencilla de rotar un ImageView
:
ACTUALIZACIÓN:
Importaciones exigidas:
import android.graphics.Matrix;
import android.widget.ImageView;
Código: (Suponiendo imageView
, angle
, pivotX
& pivotY
ya están definidos)
Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate((float) angle, pivotX, pivotY);
imageView.setImageMatrix(matrix);
Este método no requiere crear un nuevo mapa de bits cada vez.
NOTA: Para rotar un
ImageView
en ontouch en tiempo de ejecución puede set OnTouchListener onImageView
& rot it by adding last two lines (i. e. postRotate matrix & set it on ImageView ) en el código anterior sección en la parte del oyente táctil ACTION_MOVE .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-18 10:56:06
mImageView.setRotation(angle)
con API> = 11
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-24 19:39:47
Si admite API 11 o superior, puede usar el siguiente atributo XML:
android:rotation="90"
Puede que no se muestre correctamente en la vista previa xml de Android Studio, pero funciona como se esperaba.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-03 18:10:45
Hay dos maneras de hacer eso:
1 Usando Matrix
para crear un nuevo mapa de bits:
imageView = (ImageView) findViewById(R.id.imageView);
Bitmap myImg = BitmapFactory.decodeResource(getResources(), R.drawable.image);
Matrix matrix = new Matrix();
matrix.postRotate(30);
Bitmap rotated = Bitmap.createBitmap(myImg, 0, 0, myImg.getWidth(), myImg.getHeight(),
matrix, true);
imageView.setImageBitmap(rotated);
2 use {[4] } en el View
que desea rotar, y asegúrese de que la animación se ajuste a fillAfter=true
, duration=0
, y fromDegrees=toDgrees
<?xml version="1.0" encoding="utf-8"?>
<rotate
xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="45"
android:toDegrees="45"
android:pivotX="50%"
android:pivotY="50%"
android:duration="0"
android:startOffset="0"
/>
E Inflar la Animación en el código:
Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotation);
myView.startAnimation(rotation);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-25 00:56:07
Sé que esto es increíblemente tarde, pero fue útil para mí para que pueda ayudar a otros.
A partir de la API 11, puede establecer la rotación absoluta de una ImageView mediante programación mediante el método imageView.setRotation(angleInDegrees);
.
Por absoluto, quiero decir que puede llamar repetidamente a esta función sin tener que realizar un seguimiento de la rotación actual. Es decir, si giro pasando 15F
al método setRotation()
, y luego llamo setRotation()
de nuevo con 30F
, la rotación de la imagen con be 30 grados, no 45 grados.
Nota: Esto realmente funciona para cualquier subclase del objeto View, no solo ImageView.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-25 16:14:26
Esta es mi implementación de RotatableImageView. El uso es muy fácil: basta con copiar attrs.xml y RotatableImageView.java en su proyecto y agregue RotatableImageView a su diseño. Establezca el ángulo de rotación deseado usando ejemplo:parámetro angle.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:example="http://schemas.android.com/apk/res/com.example"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.example.views.RotatableImageView
android:id="@+id/layout_example_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="@drawable/ic_layout_arrow"
example:angle="180" />
</FrameLayout>
Si tiene algunos problemas con la visualización de la imagen, intente cambiar el código en RotatableImageView.onDraw () método o use el método draw () en su lugar.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-24 16:38:01
Pruebe esto en una vista personalizada
public class DrawView extends View {
public DrawView(Context context,AttributeSet attributeSet){
super(context, attributeSet);
}
@Override
public void onDraw(Canvas canvas) {
/*Canvas c=new Canvas(BitmapFactory.decodeResource(getResources(), R.drawable.new_minute1) );
c.rotate(45);*/
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.new_minute1), 0, 0, null);
canvas.rotate(45);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-12-21 11:04:01
Aquí hay una buena solución para poner un elemento de diseño girado para una ImageView:
Drawable getRotateDrawable(final Bitmap b, final float angle) {
final BitmapDrawable drawable = new BitmapDrawable(getResources(), b) {
@Override
public void draw(final Canvas canvas) {
canvas.save();
canvas.rotate(angle, b.getWidth() / 2, b.getHeight() / 2);
super.draw(canvas);
canvas.restore();
}
};
return drawable;
}
Uso:
Bitmap b=...
float angle=...
final Drawable rotatedDrawable = getRotateDrawable(b,angle);
root.setImageDrawable(rotatedDrawable);
Otra alternativa:
private Drawable getRotateDrawable(final Drawable d, final float angle) {
final Drawable[] arD = { d };
return new LayerDrawable(arD) {
@Override
public void draw(final Canvas canvas) {
canvas.save();
canvas.rotate(angle, d.getBounds().width() / 2, d.getBounds().height() / 2);
super.draw(canvas);
canvas.restore();
}
};
}
También, si desea rotar el mapa de bits, pero tiene miedo de OOM, puede usar una solución NDK que he hecho aquí
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:36
Simplemente escribe esto en tu onActivityResult
Bitmap yourSelectedImage= BitmapFactory.decodeFile(filePath);
Matrix mat = new Matrix();
mat.postRotate((270)); //degree how much you rotate i rotate 270
Bitmap bMapRotate=Bitmap.createBitmap(yourSelectedImage, 0,0,yourSelectedImage.getWidth(),yourSelectedImage.getHeight(), mat, true);
image.setImageBitmap(bMapRotate);
Drawable d=new BitmapDrawable(yourSelectedImage);
image.setBackground(d);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-09 04:05:26
Tengo una solución para esto. En realidad es una solución a un problema que surge después de la rotación(La imagen rectangular no se ajusta a ImagView) pero también cubre tu problema.. Aunque esta Solución tiene Animación para bien o para mal
int h,w;
Boolean safe=true;
Obtener los parámetros de ImageView no es posible al inicializar la actividad Para ello, consulte esta solución O establecer las dimensiones en un clic de un Botón Como este
rotateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(imageView.getRotation()/90%2==0){
h=imageView.getHeight();
w=imageView.getWidth();
}
.
.//Insert the code Snippet below here
}
Y el código que ejecutar cuando queremos rotar ImageView
if(safe)
imageView.animate().rotationBy(90).scaleX(imageView.getRotation()/90%2==0?(w*1.0f/h):1).scaleY(imageView.getRotation()/90%2==0?(w*1.0f/h):1).setDuration(2000).setInterpolator(new LinearInterpolator()).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
safe=false;
}
@Override
public void onAnimationEnd(Animator animation) {
safe=true;
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
}).start();
}
});
Esta solución es suficiente para el Problema anterior.Aunque reducirá la ImageView incluso si no es necesario (cuando la altura es menor que la Anchura).Si le molesta, puede agregar otro operador ternario dentro de scaleX / scaleY.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-25 18:33:23
Creo que el mejor método :)
int angle = 0;
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
angle = angle + 90;
imageView.setRotation(angle);
}
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-29 11:57:12
Lamentablemente, no creo que la haya. La clase Matrix
es responsable de todas las manipulaciones de imágenes, ya sea rotando, encogiendo/creciendo, sesgando, etc.
Http://developer.android.com/reference/android/graphics/Matrix.html
Mis disculpas, pero no puedo pensar en una alternativa. Tal vez alguien más podría ser capaz de hacerlo, pero las veces que he tenido que manipular una imagen he utilizado una Matriz.
¡Mucha suerte!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-25 00:18:21
Otra posible solución es crear su propia vista de imagen personalizada(por ejemplo RotateableImageView extends ImageView
)...y anula onDraw () para rotar el canvas/mapas de bits antes de redering en el canvas.No te olvides de restaurar el lienzo de nuevo.
Pero si va a rotar solo una instancia de la vista de imagen,su solución debería ser lo suficientemente buena.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-25 00:27:10
Sin matriz y animada:
{
img_view = (ImageView) findViewById(R.id.imageView);
rotate = new RotateAnimation(0 ,300);
rotate.setDuration(500);
img_view.startAnimation(rotate);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-09 22:31:33
Pruebe este código 100% funcionando;
En el botón girar, haga clic en escribir este código:
@Override
public void onClick(View view) {
if(bitmap==null){
Toast.makeText(getApplicationContext(), "Image photo is not yet set", Toast.LENGTH_LONG).show();
}
else {
Matrix matrix = new Matrix();
ivImageProduct.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate(90,ivImageProduct.getDrawable().getBounds().width()/2,ivImageProduct.getDrawable().getBounds().height()/2);
Bitmap bmp=Bitmap.createBitmap(bitmap, 0, 0,bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
bitmap=bmp;
ivImageProduct.setImageBitmap(bitmap);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-21 07:57:25
Si solo desea rotar la vista visualmente puede usar:
iv.setRotation(float)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-08 15:42:01
En lugar de convertir la imagen a mapa de bits y luego girarla, intente girar la vista de imagen directa como el siguiente código.
ImageView myImageView = (ImageView)findViewById(R.id.my_imageview);
AnimationSet animSet = new AnimationSet(true);
animSet.setInterpolator(new DecelerateInterpolator());
animSet.setFillAfter(true);
animSet.setFillEnabled(true);
final RotateAnimation animRotate = new RotateAnimation(0.0f, -90.0f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
animRotate.setDuration(1500);
animRotate.setFillAfter(true);
animSet.addAnimation(animRotate);
myImageView.startAnimation(animSet);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-22 11:51:18
Siga la siguiente respuesta para la rotación continua de una imageview
int i=0;
Si se hace clic en el botón rotar
imageView.setRotation(i+90);
i=i+90;
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-12 05:05:35