pie chart with rotation features in android os using achartengine library [duplicate] - java

I have a button that I want to put on a 45 degree angle. For some reason I can't get this to work.
Can someone please provide the code to accomplish this?

API 11 added a setRotation() method to all views.

You could create an animation and apply it to your button view. For example:
// Locate view
ImageView diskView = (ImageView) findViewById(R.id.imageView3);
// Create an animation instance
Animation an = new RotateAnimation(0.0f, 360.0f, pivotX, pivotY);
// Set the animation's parameters
an.setDuration(10000); // duration in ms
an.setRepeatCount(0); // -1 = infinite repeated
an.setRepeatMode(Animation.REVERSE); // reverses each repeat
an.setFillAfter(true); // keep rotation after animation
// Aply animation to image view
diskView.setAnimation(an);

Extend the TextView class and override the onDraw() method. Make sure the parent view is large enough to handle the rotated button without clipping it.
#Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.rotate(45,<appropriate x pivot value>,<appropriate y pivot value>);
super.onDraw(canvas);
canvas.restore();
}

I just used the simple line in my code and it works :
myCusstomView.setRotation(45);
Hope it works for you.

One line in XML
<View
android:rotation="45"
... />

Applying a rotation animation (without duration, thus no animation effect) is a simpler solution than either calling View.setRotation() or override View.onDraw method.
// substitude deltaDegrees for whatever you want
RotateAnimation rotate = new RotateAnimation(0f, deltaDegrees,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
// prevents View from restoring to original direction.
rotate.setFillAfter(true);
someButton.startAnimation(rotate);

Rotating view with rotate() will not affect your view's measured size. As result, rotated view be clipped or not fit into the parent layout. This library fixes it though:
https://github.com/rongi/rotate-layout

Joininig #Rudi's and #Pete's answers. I have created an RotateAnimation that keeps buttons functionality also after rotation.
setRotation() method preserves buttons functionality.
Code Sample:
Animation an = new RotateAnimation(0.0f, 180.0f, mainLayout.getWidth()/2, mainLayout.getHeight()/2);
an.setDuration(1000);
an.setRepeatCount(0);
an.setFillAfter(false); // DO NOT keep rotation after animation
an.setFillEnabled(true); // Make smooth ending of Animation
an.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {}
#Override
public void onAnimationRepeat(Animation animation) {}
#Override
public void onAnimationEnd(Animation animation) {
mainLayout.setRotation(180.0f); // Make instant rotation when Animation is finished
}
});
mainLayout.startAnimation(an);
mainLayout is a (LinearLayout) field

As mentioned before, the easiest way it to use rotation available since API 11:
android:rotation="90" // in XML layout
view.rotation = 90f // programatically
You can also change pivot of rotation, which is by default set to center of the view. This needs to be changed programatically:
// top left
view.pivotX = 0f
view.pivotY = 0f
// bottom right
view.pivotX = width.toFloat()
view.pivotY = height.toFloat()
...
In Activity's onCreate() or Fragment's onCreateView(...) width and height are equal to 0, because the view wasn't measured yet. You can access it simply by using doOnPreDraw extension from Android KTX, i.e.:
view.apply {
doOnPreDraw {
pivotX = width.toFloat()
pivotY = height.toFloat()
}
}

if you wish to make it dynamically with an animation:
view.animate()
.rotation(180)
.start();
THATS IT

#Ichorus's answer is correct for views, but if you want to draw rotated rectangles or text, you can do the following in your onDraw (or onDispatchDraw) callback for your view:
(note that theta is the angle from the x axis of the desired rotation, pivot is the Point that represents the point around which we want the rectangle to rotate, and horizontalRect is the rect's position "before" it was rotated)
canvas.save();
canvas.rotate(theta, pivot.x, pivot.y);
canvas.drawRect(horizontalRect, paint);
canvas.restore();

fun rotateArrow(view: View): Boolean {
return if (view.rotation == 0F) {
view.animate().setDuration(200).rotation(180F)
true
} else {
view.animate().setDuration(200).rotation(0F)
false
}
}

That's simple,
in Java
your_component.setRotation(15);
or
your_component.setRotation(295.18f);
in XML
<Button android:rotation="15" />

Related

ImageView Animation snapping back to orginial position for split second

I have a spinning wheel, which is an ImageView, in my app, and the animation is working well, but the issue is for just a split second it snaps back to it's original position (0 degree rotation). The .gif below shows what I am talking about.
The last split second of the rotation it has that awkward snap back that makes the animation look extremely unsmooth.
I am looking for a way to fix this but I cannot quite figure it out. This is my code right now that animates the ImageView and rotates it to the final position of the animation
ImageView readyButton = findViewById(R.id.spinnerready);
final ImageView spinnerSpin = findViewById(R.id.spinnerspin);
final Animation animRotate = new RotateAnimation(ROTATE_FROM, ROTATE_TO, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
animRotate.setDuration(5000);
animRotate.setRepeatCount(0);
readyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
float newDeg = ROTATE_TO;
spinnerSpin.startAnimation(animRotate);
spinnerSpin.postDelayed(new Runnable() {
#Override
public void run() {
spinnerSpin.setRotation(ROTATE_TO);
}
}, 5000);
while(newDeg > 360) {
newDeg = newDeg - 360;
}
}
});
I have also tried changing the delay of the rotation to 4500 instead of 5000 but the issue is not fixed. Is there a way to eliminate the ImageView from going back to its original position after the animation?

How can I interact with animations?

I have an animation that slides across the screen, while the animation is playing I want it to disapear if it has been clicked!
I have tried to use OnClickListener() and also OnClickMethods, both only work after the animation has finished playing!
TranslateAnimation animation = new TranslateAnimation(answer, answer, 0, height * -1); // xfrom , xto, y from,y to
animation.setDuration(5000);
Floater0.startAnimation(animation);
animation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
if (AdPlayer0.isPlaying()) {
answer = rn.nextInt(width) + 1; //useless
TranslateAnimation animation0 = new TranslateAnimation(answer, answer, 0, height * -1); // xfrom , xto, y from,y to
animation0.setDuration(5000);
animation0.setFillEnabled(true);
Floater1.startAnimation(animation0);
Floater1.setVisibility(View.VISIBLE);
Floater0.startAnimation(animation);
}
}
});
I was reading the answer here and something interesting was mentioned:
Animations do NOT effect the 'physical' location of the views on screen. If you want it to actually move then you need to adjust the properties of the view.
I have now tested the above quote, and it seems to be true! I have also looked into how to adjust the position properties of the view after the animation has ended, however I want to change its position before an animation has ended(While its playing)!
Any suggestions for a work around? ideally I would want to change the physical position of the view while the animation is played!
A TranslationAnimation only moves the pixels on the screen, so an OnClickListener does not animate with it. Use ViewPropertyAnimator instead and set an OnClickListener then it should work.
The code would look something like this :
Floater1.animate().setDuration(5000).translationX(answer).translationY(height * -1);
Check out all the available methods in the docs.
Edit/Update :
.translationX(float toX)
means -> animate the view to this point on the x axis.
The animation always starts at the current position of the view, so you don't need a fromX. There are also other methods which you can use :
.translationXBy(float byX)
.translationYBy(float byY)
With these you can translate the view BY the float value, and not TO a certain point on the screen.

Swipe between filtered images for android

Essentially, I am re-asking this question but for implementing it on android.
I am trying to allow users to swipe between filters on a static image.
The idea is that the image stays in place while the filter scrolls
above it. Snapchat recently released a version which implements this
feature. This video shows exactly what I'm trying to accomplish at
1:05.
I tried filling a list with the overlays and paging through it with the onFling and drawing with onDraw, but I lose the animations. Is there a way this can be done with ViewPager?
EDIT: As requested, I have provided my implementation for overlay view paging. It fills the viewpager with transparent png images which sits on top of an image view. Also, this code is in C#, as I am using Xamarin Android. It's fairly similar to Java for those unfamiliar with C#
...
static List<ImageView> overlayList = new List<ImageView>();
...
public class OverlayFragmentAdapter : FragmentPagerAdapter
{
public OverlayFragmentAdapter(Android.Support.V4.App.FragmentManager fm) : base(fm)
{
}
public override int Count
{
get { return 5; } //hardcoded temporarily
}
public override Android.Support.V4.App.Fragment GetItem(int position)
{
return new OverlayFragment ();
}
}
public class OverlayFragment : Android.Support.V4.App.Fragment
{
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.Inflate (Resource.Layout.fragment_overlay, container, false);
LinearLayout l1 = view.FindViewById<LinearLayout> (Resource.Id.overlay_container);
ImageView im = new ImageView (Activity);
im.SetImageResource (Resource.Drawable.Overlay); //Resource.Drawable.Overlay is a simple png transparency I created. R
l1.AddView (im);
overlayList.AddElement (im);
return view;
}
}
Activity Layout XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="bottom">
<ImageView
android:id="#+id/background_image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<RelativeLayout <!-- This second layout is for buttons which I have omitted from this code -->
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/edit_layout">
<android.support.v4.view.ViewPager
android:id="#+id/overlay_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</RelativeLayout>
Fragment Overlay XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/overlay_container"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center" />
To briefly summarize: the viewpager sits on top of the first imageview, which acts as a background. The OnCreateView method creates an overlay fragment and an overlay imageview from a resource, which it puts inside the overlay_container layout. Saving the image (Which I have not posted as it is outside the scope of this question) is simple, all it does is create a background bitmap, an overlay bitmap, and uses a canvas to draw the overlay onto the background, then writes to file.
I've worked on something similar myself.
For your specific use case, I would just use a canvas and alpha blend the filters across, on fling, as the top image.
To do the alpha blending, set the alpha paint of the first image (the original) to 255 and the alpha of the second one (the filter) to something like 128.
You just need a filter with the size of the image and then you shift the position of the second image as you draw it. That's it.
It's extremely fast and works a treat on very, very old devices.
Here's a sample implementation:
Bitmap filter, // the filter
original, // our original
tempBitmap; // the bitmap which holds the canvas results
// and is then drawn to the imageView
Canvas mCanvas; // our canvas
int x = 0; // The x coordinate of the filter. This variable will be manipulated
// in either onFling or onScroll.
void draw() {
// clear canvas
mCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
// setup paint
paint0.setAlpha(255); // the original needs to be fully visible
paint1.setAlpha(128); // the filter should be alpha blended into the original.
// enable AA for paint
// filter image
paint1.setAntiAlias(true);
paint1.setFlags(Paint.ANTI_ALIAS_FLAG); // Apply AA to the image. Optional.
paint1.setFlags(Paint.FILTER_BITMAP_FLAG); // In case you scale your image, apple
// bilinear filtering. Optional.
// original image
paint0.setAntiAlias(true);
paint0.setFlags(Paint.ANTI_ALIAS_FLAG);
paint0.setFlags(Paint.FILTER_BITMAP_FLAG);
// draw onto the canvas
mCanvas.save();
mCanvas.drawBitmap(original, 0,0,paint0);
mCanvas.drawBitmap(filter, x,0,paint1);
mCanvas.restore();
// set the new image
imageView.setImageDrawable(new BitmapDrawable(getResources(), tempBitmap));
}
And here are basic onFling and onScroll implementations.
private static final int SWIPE_DISTANCE_THRESHOLD = 125;
private static final int SWIPE_VELOCITY_THRESHOLD = 75;
// make sure to have implemented GestureDetector.OnGestureListener for these to work.
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) >
SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
// change picture to
if (distanceX > 0) {
// start left increment
}
else { // the left
// start right increment
}
}
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
// checks if we're touching for more than 2f. I like to have this implemented, to prevent
// jerky image motion, when not really moving my finger, but still touching. Optional.
if (Math.abs(distanceY) > 2 || Math.abs(distanceX) > 2) {
if(Math.abs(distanceX) > Math.abs(distanceY)) {
// move the filter left or right
}
}
}
Note: The onScroll/onFling implementations have pseudo code for the x adjustments, as those functions need to be tested. Someone who ends up implementing this in the future, can feel free to edit the answer and provide those functions.
Take a look in the implementation of the method onDraw for the default Calendar app: DayView.
There is onFling implementation and redrawing of the content (for example, calendar grid) according to the motion changes, which imitates fling.
Then you can use ColorFilter in onDraw according to the motion changes. It is very fast.
Alternatively, you can use ViewSwitcher with a list of filtered images (or somehow created a filtered images cache). To achieve the possibility of "drawing over the image", you can use ImageView and ViewSwitcher in RelativeLayout one above another and set the new filtered image in ImageView after the end of scrolling.
For this application i feel it would be most easy to use androids animation features and set the animations value to the filter you want. So you would make your own animation the changed filters iterating over your array.

Animate Status Bar Color on DrawerLayout - Material Design

I'm writing a simple app that implements a material design compliant nav drawer as described by this Stack post: https://stackoverflow.com/a/27153313/1621380
The ScrimInsetsFrameLayout works great and everything is dandy until I attempt to programmatically change the color of the status bar. My app uses the Palette API to change the toolbar and status bar color dynamically.
I'm using the property animation api to animate the toolbar and it works great! but I try to do the same animation on the statusbar and it doesn't seem to want to animate. Here's an example
Here is the code for my animator:
public static void fadeStatusBar(final DrawerLayout layout, Integer from, Integer to) {
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), from, to);
colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animator) {
layout.setStatusBarBackgroundColor((Integer) animator.getAnimatedValue());
}
});
colorAnimation.start();
}
}
Note: That same code is fading the toolbar, so its proven to work.
My question is; does anyone know of a way to get a smooth transition when using DrawerLayout.setStatusBarBackgorundColour()?
Note: I have used the Window method window.setStatusBarColor() method, and it animates fine but breaks the "transparent statusbar" when the NavDrawer is pulled in.
As advised #adneal's comment on my original question the answer was to invalidate the view during the animation.
DrawerLayout calculates the top inset and draws the status bar background itself. So, you just need to make a call to View.invalidate to force it to redraw while the animation is being updated. #adneal
I've updated my code to this
ValueAnimator colorAnimation = ValueAnimator.ofArgb(from, to);
colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animator) {
layout.invalidate();
layout.setStatusBarBackgroundColor((Integer) animator.getAnimatedValue());
}
});
colorAnimation.start();
For anyone wondering why this worked, I found this stack post enlightening: When it's necessary to execute invalidate() on a View?
you can do this Easily like below:
1 - set your statusbar color to transparent by using this:
<item name="colorPrimaryDark">#android:color/transparent</item>
2 - define application's view to change it background:
View root = *A_view_on_the_activity*.getRootView();
3 - then add this function to your project:
private void color_change(final View view,int from_color,int to_color){
final float[] from = new float[3],
to = new float[3];
String hexColor_from = String.format("#%06X", (0xFFFFFF & from_color));
String hexColor_to = String.format("#%06X", (0xFFFFFF & to_color));
Color.colorToHSV(Color.parseColor(hexColor_from), from); // from
Color.colorToHSV(Color.parseColor(hexColor_to), to); // to
ValueAnimator anim = ValueAnimator.ofFloat(0, 1); // animate from 0 to 1
anim.setDuration(600); // for 300 ms
final float[] hsv = new float[3]; // transition color
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener(){
#Override public void onAnimationUpdate(ValueAnimator animation) {
// Transition along each axis of HSV (hue, saturation, value)
hsv[0] = from[0] + (to[0] - from[0])*animation.getAnimatedFraction();
hsv[1] = from[1] + (to[1] - from[1])*animation.getAnimatedFraction();
hsv[2] = from[2] + (to[2] - from[2])*animation.getAnimatedFraction();
view.setBackgroundColor(Color.HSVToColor(hsv));
}
});
anim.start();
}
4 - and then change the hole application's background color animation by using the function that Written above:
color_change(root, from_color, to_color);

Android ViewGroup.setScaleX() cause the view to be clipped

I use NineOldAndroids library to scale my custom layout.
public class MyLayout extends FrameLayout {
// LayoutParams.MATCH_PARENT and all.
...
#Override
public boolean setPositionAndScale(ViewGroup v, PositionAndScale pas, PointInfo pi) {
...
mScale = pas.getScale();
ViewHelper.setScaleX(this, mScale);
ViewHelper.setScaleY(this, mScale);
}
}
I have tried FrameLayout and AbsoluteLayout. All have the same effect.
When mScale < 1.0 scaling/zooming works but part of the layout is clipped.
mScale = 1.0:
mScale < 1.0: scaling/zooming works but layout is clipped
How can i fix this issue?
Edit: The picture was taken on ICS. So I don't think it's NineOldAndroids problem.
The parent of your view must have the property android:clipChildren disabled (from layout file or with setClipChildren(false) ).
But with this method you don't get the touch events outside the view clip bounds. You can work around by sending them from your activity or writing a custom ViewGroup parent.
I'm using a different hack which seems to work in my case, the trick is to maintain your own transformation matrix. Then, you have to overload a lot of ViewGroup's method to make it work. For example :
#Override
protected void dispatchDraw(Canvas canvas) {
Log.d(TAG, "dispatchDraw " + canvas);
canvas.save();
canvas.concat(mMatrix);
super.dispatchDraw(canvas);
canvas.restore();
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
Log.d(TAG, "dispatchTouchEvent " + ev);
ev.transform(getInvMatrix()); //
return super.dispatchTouchEvent(ev);
}
private Matrix getInvMatrix()
{
if(!mTmpMatIsInvMat)
mMatrix.invert(mTmpMat);
mTmpMatIsInvMat = true;
return mTmpMat;
}
In case anyone got in to the same situation as me.
I ended up using this approach:
protected void setScale(float scale, boolean updateView) {
mScale = scale;
if (updateView) {
LayoutParams params = getLayoutParams();
onUpdateScale(scale, params);
setLayoutParams(params);
}
}
protected void onUpdateScale(float scale, LayoutParams params) {
params.leftMargin = (int) (mModel.getX() * scale);
params.topMargin = (int) (mModel.getY() * scale);
params.width = (int) (mModel.getWidth() * scale);
params.height = (int) (mModel.getHeight() * scale);
}
Since API Level 11, the View class has setScaleX() and setScaleY() methods, that work as expected and also scale sub-views of the scaled view. So, if that'd be a way for you, drop the library and just do
v.setScaleX(mScale);
v.setScaleY(mScale);
If I understand your problem correctly, you are scaling a view group and expect the included views to scale accordingly. It doesn't work that way: you scale the view group and it changes size, but its children views do not.
Just scale all subviews. Even so, I am not sure that texts and images are going to be automatically scaled. What you want is zoom, not scale. Try this reference.
Use ViewGroup.layout. It may be the easiest way to scale(&move) ViewGroup.

Categories