voltear sola samsung porque por pantalla online imagen grados girar gira fotos espejo como celular android bitmap rotation imageview

sola - Android: gira la imagen en la vista de la imagen desde un ángulo



porque no gira la pantalla de mi samsung (16)

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);


Aquí hay una buena solución para poner un drawable girado para un 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(); } }; }

Además, si desea rotar el mapa de bits, pero le teme a OOM, puede usar una solución NDK que hice here


En lugar de convertir la imagen a mapa de bits y luego girarla, intente girar la vista de la imagen directa como el código siguiente.

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);


Esta es mi implementación de RotatableImageView . El uso es muy fácil: solo copie attrs.xml y RotatableImageView.java en su proyecto y agregue RotatableImageView a su diseño. Establezca el ángulo de rotación deseado con el ejemplo: parámetro de ángulo .

<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 problemas para mostrar la imagen, intente cambiar el código en el método RotatableImageView.onDraw () o use el método draw () en su lugar.


Hay dos maneras de hacerlo:

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 RotateAnimation en la View que desea Girar, y asegúrese de que la Animación se configure para 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 infle la animación en el código:

Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotation); myView.startAnimation(rotation);


Otra forma simple de rotar un ImageView :
ACTUALIZAR:
Importaciones requeridas:

import android.graphics.Matrix; import android.widget.ImageView;

Código: (Asumiendo que imageView , angle , pivotX y 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 la creación de un nuevo mapa de bits cada vez.

NOTA: Para rotar un ImageView en ontouch en tiempo de ejecución, puede configurar TouchTouchListener en ImageView y rotarlo agregando las dos últimas líneas (por ejemplo, matriz de postRotate y configurarlo en imageView ) en la sección de código anterior en su parte ACTION_MOVE de detector táctil .


Otra posible solución es crear su propia vista de imagen personalizada (digamos que RotateableImageView extends ImageView ) ... y anular el onDraw () para rotar los lienzos / mapas de bits antes de releer al lienzo. No olvide restaurar el lienzo.

Pero si va a rotar solo una instancia de vista de imagen, su solución debería ser lo suficientemente buena.


Pruebe este código 100% funcionando;

Al girar el botón, 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); } }


Sé que esto es increíblemente tarde, pero fue útil para mí, por lo que puede ayudar a otros.

A partir de API 11, puede establecer la rotación absoluta de un ImageView mediante programación mediante el uso de imageView.setRotation(angleInDegrees); método.

Por absoluto, quiero decir que puede llamar repetidamente esta función sin tener que hacer un seguimiento de la rotación actual. Es decir, si giro pasando 15F al método setRotation() y luego setRotation() llamar a setRotation() con 30F , la rotación de la imagen será de 30 grados, no de 45 grados.

Nota: Esto realmente funciona para cualquier subclase del objeto Ver , no solo para ImageView.


Si admite API 11 o superior, puede usar el siguiente atributo XML:

android:rotation="90"

Es posible que no se muestre correctamente en la vista previa de Android Studio xml, pero funciona como se esperaba.


Si solo desea rotar la vista visualmente, puede usar:

iv.setRotation(float)


Tengo una solution 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 su problema. Aunque esta solución tiene animación para bien o para mal

int h,w; Boolean safe=true;

No es posible obtener los parámetros de imageView en la inicialización de la actividad. Para hacerlo, consulte esta solution O establezca las dimensiones en onClick of a Button Like this

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 se 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 imagen vista incluso si no es necesaria (cuando la altura es menor que el ancho). Si le molesta, puede agregar otro operador ternario dentro de scaleX / scaleY.


Tristemente, no creo que exista. La clase Matrix es responsable de todas las manipulaciones de la imagen, ya sea girando, 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 pueda, pero las veces que he tenido que manipular una imagen he usado Matrix.

¡La mejor de las suertes!


prueba 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); } }


sin matriz y animado:

{ img_view = (ImageView) findViewById(R.id.imageView); rotate = new RotateAnimation(0 ,300); rotate.setDuration(500); img_view.startAnimation(rotate); }


solo escriba esto en su 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);


mImageView.setRotation(angle) con API> = 11