I need to create a circle that rotates and contains data for my application. Should I create a customized object for my application or should I make a in-application widget?
While on the topic, how do you refer to a widget within an application instead of a stand alone widget for the android desktop?
This is a rotatable LinearLayout that you can put everything in it and you can rotate it by degree if you customize it. use rotate() method to rotate it and...
enjoy! ;)
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.LinearLayout;
public class RotateLinearLayout extends LinearLayout {
private Matrix mForward = new Matrix();
private Matrix mReverse = new Matrix();
private float[] mTemp = new float[2];
private float degree = 0;
public RotateLinearLayout(Context context) {
super(context);
}
public RotateLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void dispatchDraw(Canvas canvas) {
try {
if (degree == 0) {
super.dispatchDraw(canvas);
return;
}
canvas.rotate(degree, getWidth() / 2, getHeight() / 2);
mForward = canvas.getMatrix();
mForward.invert(mReverse);
canvas.save();
canvas.setMatrix(mForward); // This is the matrix we need to use for
// proper positioning of touch events
super.dispatchDraw(canvas);
canvas.restore();
invalidate();
} catch (Exception e) {
}
}
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (degree == 0) {
return super.dispatchTouchEvent(event);
}
// final float[] temp = mTemp;
// temp[0] = event.getX();
// temp[1] = event.getY();
// mReverse.mapPoints(temp);
// event.setLocation(temp[0], temp[1]);
event.setLocation(getWidth() - event.getX(), getHeight() - event.getY());
return super.dispatchTouchEvent(event);
}
public void rotate() {
if (degree == 0) {
degree = 180;
} else {
degree = 0;
}
}
}
Update:
add this code to your xml layout and put your Views like ImageView or another LinearLayout in it :
<org.mabna.order.ui.RotateLinearLayout android:id="#+id/llParent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:gravity="center"
android:orientation="horizontal" >
<ImageView
android:id="#+id/myImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:src="#drawable/main01" />
</org.mabna.order.ui.RotateLinearLayout>
in onCreate() method:
llParent = (RotateLinearLayout) this.findViewById(R.id.llParent);
in onClickListener of a button:
protected void btnRotate_onClick() {
llParent.rotate();
}
Update2:
You can use an animation for rotation before real rotation (llParent.rotate();). it needs an animation layout like rotate_dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000" android:fromDegrees="-180" android:toDegrees="0"
android:pivotX="50%" android:pivotY="50%" android:fillAfter="true" />
and in your code:
protected void btnRotate_onClick() {
// rotate
Animation rotateAnimation = AnimationUtils.loadAnimation(this,
R.anim.rotate_dialog);
llParent.startAnimation(rotateAnimation);
llParent.rotate();
}
There is a fairly easy way to make a rotating animation from a custom widget derived from the View class. After the view is created and placed in your layout, you can call View.setAnimation(Animation) or View.startAnimation(Animation), supplying a RotateAnimation on the view to start it. Here is an example of a rotation animation defined in xml, that can be loaded from your activity with getResources().getAnimation(int).
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="float"
android:toDegrees="float"
android:pivotX="float"
android:pivotY="float" />
I am using the following code to rotate a image in ImageView by an angle. Is there any simpler and less complex method available.
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);
mImageView.setRotation(angle) with API>=11
Another simple way to rotate an ImageView:
UPDATE:
Required imports:
import android.graphics.Matrix;
import android.widget.ImageView;
Code: (Assuming imageView, angle, pivotX & pivotY are already defined)
Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate((float) angle, pivotX, pivotY);
imageView.setImageMatrix(matrix);
This method does not require creating a new bitmap each time.
NOTE: To rotate an ImageView on ontouch at runtime you can
set onTouchListener on ImageView & rotate it by adding last two
lines(i.e. postRotate matrix & set it on imageView) in above code
section in your touch listener ACTION_MOVE part.
If you're supporting API 11 or higher, you can just use the following XML attribute:
android:rotation="90"
It might not display correctly in Android Studio xml preview, but it works as expected.
There are two ways to do that:
1 Using Matrix to create a new bitmap:
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 on the View you want to Rotate, and make sure the Animation set to fillAfter=true, duration=0, and 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"
/>
and Inflate the Animation in code:
Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotation);
myView.startAnimation(rotation);
I know this is insanely late, but it was helpful for me so it may help others.
As of API 11, you can set the absolute rotation of an ImageView programmatically by using the imageView.setRotation(angleInDegrees); method.
By absolute, I mean you can repeatedly call this function without having to keep track of the current rotation. Meaning, if I rotate by passing 15F to the setRotation() method, and then call setRotation() again with 30F, the image's rotation with be 30 degrees, not 45 degrees.
Note: This actually works for any subclass of the View object, not just ImageView.
For Kotlin,
mImageView.rotation = 90f //angle in float
This will rotate the imageView rather than rotating the image
Also, though its a method in View class. So you can pretty much rotate any view using it.
Can also be done this way:-
imageView.animate().rotation(180).start();
got from here.
Rotate an image in android with delay:
imgSplash.animate().rotationBy(360f).setDuration(3000).setInterpolator(new LinearInterpolator()).start();
This is my implementation of RotatableImageView. Usage is very easy: just copy attrs.xml and RotatableImageView.java into your project and add RotatableImageView to your layout. Set desired rotation angle using example:angle parameter.
<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>
If you have some problems with displaying image, try change code in RotatableImageView.onDraw() method or use draw() method instead.
Also, if you want to rotate an ImageView by 180 degrees vertically or horizontally, you can use scaleY or scaleX properties and set them to -1f. Here is a Kotlin example:
imageView.scaleY = -1f
imageView.scaleX = -1f
1f value is used to return an ImageView to its normal state:
imageView.scaleY = 1f
imageView.scaleX = 1f
I have a solution to this.
Actually it is a solution to a problem that arises after rotation(Rectangular image doesn't fit ImagView)
but it covers your problem too..
Although this Solution has Animation for better or for worse
int h,w;
Boolean safe=true;
Getting the parameters of imageView is not possible at initialisation of activity
To do so please refer to this solution
OR set the dimensions at 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
}
And the code to be run when we want to rotate 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();
}
});
This solution is sufficient for the Problem above.Although it will shrink the imageView even if it is not necessary(when height is smaller than Width).If it bothers you,you can add another ternary operator inside scaleX/scaleY.
I think the best method :)
int angle = 0;
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
angle = angle + 90;
imageView.setRotation(angle);
}
});
You can simply use rotation atribute of ImageView
Below is the attribute from ImageView with details from Android source
<!-- rotation of the view, in degrees. -->
<attr name="rotation" format="float" />
Sadly, I don't think there is. The Matrix class is responsible for all image manipulations, whether it's rotating, shrinking/growing, skewing, etc.
http://developer.android.com/reference/android/graphics/Matrix.html
My apologies, but I can't think of an alternative. Maybe someone else might be able to, but the times I've had to manipulate an image I've used a Matrix.
Best of luck!
try this on a custom view
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);
}
}
here's a nice solution for putting a rotated drawable for an 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;
}
usage:
Bitmap b=...
float angle=...
final Drawable rotatedDrawable = getRotateDrawable(b,angle);
root.setImageDrawable(rotatedDrawable);
another alternative:
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();
}
};
}
also, if you wish to rotate the bitmap, but afraid of OOM, you can use an NDK solution i've made here
If you only want to rotate the view visually you can use:
iv.setRotation(float)
if u want to rotate an image by 180 degrees then put these two value in imageview tag:-
android:scaleX="-1"
android:scaleY="-1"
Explanation:- scaleX = 1 and scaleY = 1 repesent it's normal state but if we put -1 on scaleX/scaleY property then it will be rotated by 180 degrees
Another possible solution is to create your own custom Image view(say RotateableImageView extends ImageView )...and override the onDraw() to rotate either the canvas/bitmaps before redering on to the canvas.Don't forget to restore the canvas back.
But if you are going to rotate only a single instance of image view,your solution should be good enough.
without matrix and animated:
{
img_view = (ImageView) findViewById(R.id.imageView);
rotate = new RotateAnimation(0 ,300);
rotate.setDuration(500);
img_view.startAnimation(rotate);
}
just write this in your 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);
Try this code 100% working;
On rotate button click write this code:
#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);
}
}
Rather than convert image to bitmap and then rotate it try to rotate direct image view like below code.
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);
Follow the below answer for continuous rotation of an imageview
int i=0;
If rotate button clicked
imageView.setRotation(i+90);
i=i+90;
Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate((float) 20, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);
imageView.setImageMatrix(matrix);
how to use?
public class MainActivity extends AppCompatActivity {
int view = R.layout.activity_main;
TextView textChanger;
ImageView imageView;
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(view);
textChanger = findViewById(R.id.textChanger);
imageView=findViewById(R.id.imageView);
textChanger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
roateImage(imageView);
}
});
}
private void roateImage(ImageView imageView) {
Matrix matrix = new Matrix();
imageView.setScaleType(ImageView.ScaleType.MATRIX); //required
matrix.postRotate((float) 20, imageView.getDrawable().getBounds().width()/2, imageView.getDrawable().getBounds().height()/2);
imageView.setImageMatrix(matrix);
}
}
It is too late for the answer, someone may found this useful, I came across a situation where I need to animate the rotation og ImageView by some angle on first ClickListener event, and then on the 2nd ClickListener event, need to rotate back the image to the original angle. this is how this magic happened
fun rotateAnim(imageView: ImageView,angle : Float){
imageView.isEnabled = false
Log.i(TAG, "onCreate: ${imageView.rotation}")
val rotation = imageView.animate().rotationBy(angle)
rotation.interpolator = FastOutSlowInInterpolator()
rotation.startDelay = 200
rotation.setListener(object : Animator.AnimatorListener{
override fun onAnimationEnd(animation: Animator?) {
imageView.isEnabled = true
}
override fun onAnimationStart(animation: Animator?) {}
override fun onAnimationCancel(animation: Animator?) {}
override fun onAnimationRepeat(animation: Animator?) {}
})
rotation.start()
}
and implementation is like
holder.itemView.setOnClickListener {
val rotation = imageView.rotation
if(rotation == 180F){
rotateAnim(imageView,90F)
}else{
rotateAnim(imageView,-90F)
}
}
Using Kotlin:
imageView.rotation = degrees.toFloat()
I wrote a suduko game for android, and want to animate tile, if the user insert wrong number.
But I don't figure how to do this? The problem is that, I have one big rectangel wich cover hole screen, and devide this rectangle in tiles, simply by drawnig lines. And now I can't figure how to animate tiles.
Hop I could explain my problem.
Sorry for bad english, and thaks for answers)
You should not draw your board like that. I would recommend to implement one tile as a subclass of View so you can then animate each one individually.
Try this to see how animation works:
Tile class
public class Tile extends View {
private RectF mRect;
private Paint mPaint;
public Tile(Context context) {
super(context);
init();
}
public Tile(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public Tile(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init(){
mRect = new RectF(0, 0, 100, 100);
mPaint = new Paint();
mPaint.setStyle( Paint.Style.STROKE );
mPaint.setColor( Color.BLUE );
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawRect(mRect, mPaint);
}
}
Main activity
public class MainActivity extends Activity implements OnClickListener {
private Tile mTile;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout layout = new LinearLayout( this );
layout.setBackgroundColor( Color.WHITE );
layout.setPadding(50, 50, 50, 50);
Button btn = new Button( this );
btn.setText( "Click Me" );
btn.setOnClickListener( this );
layout.addView( btn );
mTile = new Tile( this );
layout.addView( mTile );
setContentView( layout );
}
#Override
public void onClick(View v) {
Animation scaleAnim = AnimationUtils.loadAnimation(this, R.anim.scale);
mTile.startAnimation( scaleAnim );
}
}
Animation definition (This file should be named scale.xml and placed under directory /res/anim )
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false">
<scale
android:interpolator="#android:anim/accelerate_decelerate_interpolator"
android:fromXScale="1.0"
android:toXScale="2.0"
android:fromYScale="1.0"
android:toYScale="2.0"
android:fillAfter="false"
android:repeatCount="1"
android:repeatMode="reverse"
android:duration="700" />
</set>
Learn more about animations here.
To make your own animation have a look here here.
Hope this keeps you going.
If you use standard views, you could look into tween animation, i.e. define a set of animations, load them from the resources and attach them to your views / start the animation.
Have a look at the spaceship jump example here.
If you do custom drawing, I'm afraid you also need to do custom animation.
Working with animation on anything before Honeycomb is a real pain. I recommend downloading the NineOldAndroids library (http://nineoldandroids.com/) and using it as imports, that way you can use the Honeycomb animation API on all versions of android (even up to 1.0).
I want to rotate my own FrameLayout in 3d in android. Do i have to use GlSurfaceView class. I am new in computer graphics but know the theory behind the rotations and translations. In order to make 3d opengl rotations we do the followings generally.
In activity class we create a GLSurfaceView object and set its renderer. Renderer object is created from a class which implements GlSurfaceView.Renderer interface.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GLSurfaceView view = new GLSurfaceView(this);
view.setRenderer(new OpenGLRenderer());
setContentView(view);
}
In our Renderer class we make the drawings, rotations and translations with following methods
// Called when the surface is created or recreated.
public void onSurfaceCreated(GL10 gl, EGLConfig config)
// Called to draw the current frame.
public void onDrawFrame(GL10 gl)
// Called when the surface changed size.
public void onSurfaceChanged(GL10 gl, int width, int height)
However i have a custom framelayout which is declared as
public class RotatedMapView extends FrameLayout
I want to make this :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RotatedMapView view = new RotatedMapView (this);
view.setRenderer(new OpenGLRenderer());
setContentView(view);
}
But i can't, because setRenderer is special for GlSurfaceView. I am now browsing the GlSurfaceView.java source code in order to adapt it to my design. The link i found for GlSurfaceVÄ°ew.java is http://code.google.com/p/apps-for-android/source/browse/trunk/SpriteMethodTest/src/com/android/spritemethodtest/GLSurfaceView.java?r=150
The source is too long. In fact I am not lazy to read it but i want to be sure whether or not i am in correct way.
Now i am looking at animations which i have never used. In api demos there is a rotation example over y axis. I want to make rotation over x. It is succesful for negative angles but in positive direction it disappears the view. The function is below.
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final float fromDegrees = mFromDegrees;
float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);
final float centerX = mCenterX;
final float centerY = mCenterY;
final Camera camera = mCamera;
final Matrix matrix = t.getMatrix();
camera.save();
if (mReverse) {
camera.translate(0.0f, 0.0f, mDepthZ * interpolatedTime);
} else {
camera.translate(0.0f, 0.0f, mDepthZ * (1.0f - interpolatedTime));
}
camera.rotateY(degrees);
`camera.rotateX(degrees); //i want to do this it works for negative but not` //positive angles
camera.getMatrix(matrix);
camera.restore();
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
}
Framelayouts (and anything extending View) are designed to be drawn on a Canvas element in 2D. It is not possible to draw these using openGL. If you want to draw a GUI in 3D/GL then you will have to code that up from scratch or find a library which has already done this. I'm sure there are a few out there but I haven't had the need for one yet.
You can get some fake looking 3D effects on views by using scale animations, though these will only work if the animation is done fast so the user doesn't notice. This probably isn't what you are after.
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale
android:fromXScale="1.0" android:toXScale="0.0"
android:fromYScale="1.0" android:toYScale="1.0"
android:pivotX="50%" android:pivotY="0%"
android:duration="#android:integer/config_shortAnimTime"
/>
Is it possible to create a drawable that has some sort of animation, whether it is a frame by frame animation, rotation, etc, that is defined as a xml drawable and can be represented by a single Drawable object without having to deal with the animation in code?
How I am thinking to use it:
I have a list and each item in this list may at sometime have something happening to it. While it is happening, I would like to have a spinning progress animation similar to a indeterminate ProgressBar. Since there may also be several of these on screen I thought that if they all shared the same Drawable they would only need one instance of it in memory and their animations would be synced so you wouldn't have a bunch of spinning objects in various points in the spinning animation.
I'm not attached to this approach. I'm just trying to think of the most efficient way to display several spinning progress animations and ideally have them synced together so they are consistent in appearance.
Thanks
In response to Sybiam's answer:
I have tried implementing a RotateDrawable but it is not rotating.
Here is my xml for the drawable so far:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="#drawable/my_drawable_to_rotate"
android:fromDegrees="0"
android:toDegrees="360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="800"
android:visible="true" />
I have tried using that drawable as the src and background of a ImageView and both ways only produced a non-rotating image.
Is there something that has to start the image rotation?
Yes! The (undocumented) key, which I discovered by reading the ProgressBar code is that you have to call Drawable.setLevel() in onDraw() in order for the <rotate> thing to have any effect. The ProgressBar works something like this (extra unimportant code omitted):
The drawable XML:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<rotate
android:drawable="#drawable/spinner_48_outer_holo"
android:pivotX="50%"
android:pivotY="50%"
android:fromDegrees="0"
android:toDegrees="1080" />
</item>
<item>
<rotate
android:drawable="#drawable/spinner_48_inner_holo"
android:pivotX="50%"
android:pivotY="50%"
android:fromDegrees="720"
android:toDegrees="0" />
</item>
</layer-list>
In onDraw():
Drawable d = getDrawable();
if (d != null)
{
// Translate canvas so a indeterminate circular progress bar with
// padding rotates properly in its animation
canvas.save();
canvas.translate(getPaddingLeft(), getPaddingTop());
long time = getDrawingTime();
// I'm not sure about the +1.
float prog = (float)(time % ANIM_PERIOD+1) / (float)ANIM_PERIOD;
int level = (int)(MAX_LEVEL * prog);
d.setLevel(level);
d.draw(canvas);
canvas.restore();
ViewCompat.postInvalidateOnAnimation(this);
}
MAX_LEVEL is a constant, and is always 10000 (according to the docs).
ANIM_PERIOD is the period of your animation in milliseconds.
Unfortunately since you need to modify onDraw() you can't just put this drawable in an ImageView since ImageView never changes the drawable level. However you may be able to change the drawable level from outside the ImageView's. ProgressBar (ab)uses an AlphaAnimation to set the level. So you'd do something like this:
mMyImageView.setImageDrawable(myDrawable);
ObjectAnimator anim = ObjectAnimator.ofInt(myDrawable, "level", 0, MAX_LEVEL);
anim.setRepeatCount(ObjectAnimator.INFINITE);
anim.start();
It might work but I haven't tested it.
Edit
There is actually an ImageView.setImageLevel() method so it might be as simple as:
ObjectAnimator anim = ObjectAnimator.ofInt(myImageVew, "ImageLevel", 0, MAX_LEVEL);
anim.setRepeatCount(ObjectAnimator.INFINITE);
anim.start();
Drawables
There you go! And this one for RotateDrawable. I believe that from the Doc it should be pretty straitght forward. You can define everything in a xml file and set the background of a view as the drawable xml. /drawable/myrotate.xml -> #drawable/myrotate
Edit:
This is an answer I found here.
Drawable Rotating around its center Android
Edit 2:
You are right the RotateDrawable seem broken. I don't know I tried it too. I haven't yet succeded in making it animate. But I did succed to rotate it. You have to use setLevel which will rotate it. Though it doesn't look really useful. I browsed the code and the RotateDrawable doesn't even inflate the animation duration and the current rotation seems strangely use the level as a measure for rotation. I believe you have to use it with a AnimationDrawable but here again. It just crashed for me. I haven't used that feature yet but planned to use it in the future. I browsed the web and the RotateDrawable seems to be very undocumented like almost every Drawable objects.
Here is one of possible ways (especially useful when you have a Drawable somewhere set and need to animate it). The idea is to wrap the drawable and decorate it with animation. In my case, I had to rotate it, so below you can find sample implementation:
public class RotatableDrawable extends DrawableWrapper {
private float rotation;
private Rect bounds;
private ObjectAnimator animator;
private long defaultAnimationDuration;
public RotatableDrawable(Resources resources, Drawable drawable) {
super(vectorToBitmapDrawableIfNeeded(resources, drawable));
bounds = new Rect();
defaultAnimationDuration = resources.getInteger(android.R.integer.config_mediumAnimTime);
}
#Override
public void draw(Canvas canvas) {
copyBounds(bounds);
canvas.save();
canvas.rotate(rotation, bounds.centerX(), bounds.centerY());
super.draw(canvas);
canvas.restore();
}
public void rotate(float degrees) {
rotate(degrees, defaultAnimationDuration);
}
public void rotate(float degrees, long millis) {
if (null != animator && animator.isStarted()) {
animator.end();
} else if (null == animator) {
animator = ObjectAnimator.ofFloat(this, "rotation", 0, 0);
animator.setInterpolator(new AccelerateDecelerateInterpolator());
}
animator.setFloatValues(rotation, degrees);
animator.setDuration(millis).start();
}
#AnimatorSetter
public void setRotation(float degrees) {
this.rotation = degrees % 360;
invalidateSelf();
}
/**
* Workaround for issues related to vector drawables rotation and scaling:
* https://code.google.com/p/android/issues/detail?id=192413
* https://code.google.com/p/android/issues/detail?id=208453
*/
private static Drawable vectorToBitmapDrawableIfNeeded(Resources resources, Drawable drawable) {
if (drawable instanceof VectorDrawable) {
Bitmap b = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
drawable.setBounds(0, 0, c.getWidth(), c.getHeight());
drawable.draw(c);
drawable = new BitmapDrawable(resources, b);
}
return drawable;
}
}
and you can use it like this (rotating toolbar navigation icon 360 degrees):
backIcon = new RotatableDrawable(getResources(), toolbar.getNavigationIcon().mutate());
toolbar.setNavigationIcon(backIcon);
backIcon.rotate(360);
It shouldn't be hard to add a method that will rotate it indefinite (setRepeatMode INFINITE for animator)
You can start from studying the ProgressBar2 from API Demos project (it is available as a part of the SDK). Specifically pay attention to R.layout.progressbar_2.
I take back to life this post just to post my solution with vector drawable:
So you need 1 vector drawable in drawable resource (#drawable/ic_brush_24dp):
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24.0"
android:viewportHeight="24.0">
<group
android:name="rotation" <---- target name of animated-vector
android:pivotX="12.0"
android:pivotY="12.0"
android:rotation="0.0"> <--- propertyName of animator
<path
android:fillColor="#FF000000"
android:pathData="M7,14c-1.66,0 -3,1.34 -3,3 0,1.31 -1.16,2 -2,2 0.92,1.22 2.49,2 4,2 2.21,0 4,-1.79 4,-4 0,-1.66 -1.34,-3 -3,-3zM20.71,4.63l-1.34,-1.34c-0.39,-0.39 -1.02,-0.39 -1.41,0L9,12.25 11.75,15l8.96,-8.96c0.39,-0.39 0.39,-1.02 0,-1.41z" />
</group>
</vector>
Then you need your animator in animator resource folder (#animator/pendulum)
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator
android:duration="350"
android:repeatCount="infinite"
android:repeatMode="reverse"
android:propertyName="rotation"
android:valueFrom="0.0"
android:valueTo="-90.0" />
</set>
Then you need your animated-vector in drawable resource (#drawable/test_anim_brush2):
<?xml version="1.0" encoding="utf-8"?>
<animated-vector xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="#drawable/ic_brush_24dp">
<target
android:name="rotation"
android:animation="#animator/pendulum" />
</animated-vector>
Then you need to extend ImageView (because that's the only way i found to start the animation)
public class ImageView extends AppCompatImageView{
public ImageView(Context context){
super(context);
init(context, null, 0);
}
public ImageView(Context context, AttributeSet attrs){
super(context, attrs);
init(context, attrs, 0);
}
public ImageView(Context context, AttributeSet attrs, int defStyleAttr){
super(context, attrs, defStyleAttr);
init(context, attrs, 0);
}
private void init(Context context, AttributeSet attrs, int defStyleAttr){
}
#Override
protected void onAttachedToWindow(){
super.onAttachedToWindow();
Drawable d = getBackground();
if(d instanceof AnimatedVectorDrawable){
AnimatedVectorDrawable anim = (AnimatedVectorDrawable)d;
anim.start();
}
}
#Override
protected void onDetachedFromWindow(){
super.onDetachedFromWindow();
Drawable d = getBackground();
if(d instanceof AnimatedVectorDrawable){
AnimatedVectorDrawable anim = (AnimatedVectorDrawable)d;
anim.stop();
}
}
}
And then add your imageView to your layout :
<ui.component.ImageView
android:id="#+id/test_anim_brush"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center_horizontal"
android:background="#drawable/test_anim_brush2"/>
Pro :
You can fully define your animation in xml with object animator (duration, interpolator, etc...)
Works with everything which accept drawable (as long as you add at good place the start animator)
Con:
Works only with vector
Still need to add your custom start by extending class or whenever you think it is smart...
private ValueAnimator rotateDrawable(RotateDrawable drawable, int fromDegree, int toDegree) {
drawable.setFromDegrees(fromDegree);
drawable.setToDegrees(toDegree);
return ObjectAnimator.ofInt(drawable, "level", 0, 10000);
}
level is the interpulting value from 0 to 100000. the actual animation values are set by the setter methods
you can use stateListAnimator
<ImageView
android:id="#+id/your_id"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="#drawable/your_drawable"
android:stateListAnimator="#anim/bounce" />
and bounce
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="#android:anim/bounce">
<translate
android:duration="900"
android:fromXDelta="100%p"
android:toXDelta="0%p" />
</set>