Wednesday, April 24, 2013

Basic animations in Andorid



I would like to note down the basic animations which I worked out in Android.
  
Let us start with some attributes and tags before we actually start writing down the anim.xml 

  • translate - Tag to translate the view from certain x% to certain x% 
  • ex : <translate android:toXDelta="0%p" android:fromXDelta="50%p"/> 
  • In the above ex, I'm transalating the view from 0% in parent to 100% in parent. 
  • If you want to start at the actual point of View remove p from 0%p and 100%p. This will animate from 0% of view's X position to 100% of view's X. 
  • alpha - Tag which mention's the visibility of the view over a particular interval of animation 
  • ex :<alpha android:duration="@android:integer/config_mediumAnimTime" android:toAlpha="1.0"android:fromAlpha="0.0"/> 
  • In above ex, fromAlpha value 0 represent's the view is in complete invisible state. Upon the duration the visibility increases. 
  •  The duration value is 400ms. So, the view will be compltely visibile after 400ms. 
  • duration - The amount of time to play animation. It is measured in milliseconds. 

Depending on the direction, duration of play and fading( alpha ) we can make many combinations of animations. I will discuss the main anim's which will be used very frequently. These are listed below. 

  • Left in 
  • Let out 
  • Right in 
  • Right Out 
  • Bottom in 
  • Bottom Out 
  • Top in  
  • Top Out  

Out of the above 8 types, if we understand first 2 then we can automatically write down others's easily.  

Left-In:  
     Meaning it will be started from left side of the parent and will pierce into the parent.XML will look like 

<set xmlns:android="http://schemas.android.com/apk/res/android" > <translate android:duration="@android:integer/config_mediumAnimTime" android:fromXDelta="-50p%" android:toXDelta="0%p" /> <alpha android:duration="@android:integer/config_mediumAnimTime" android:fromAlpha="0.0" android:toAlpha="1.0" /> </set>

The above animation will start from 50% outside the parent and will animate upto 0% of the parent while applying the alpha value within a duration of 400ms. 

Left-out: 
     Meaning it will be move out of it's parent starting at 0% of its parent and it will end at -50%.It will look like 

<set xmlns:android="http://schemas.android.com/apk/res/android" > <translate android:duration="@string/anim_duration" android:fromXDelta="0%" android:toXDelta="-50%" /> <alpha android:duration="@android:integer/config_mediumAnimTime" android:fromAlpha="1.0" android:toAlpha="0" /> </set>  

Applying these animations to a view involves 3 steps. 
  • Load animation. 
  • Add animatinlistener to the animation. 
  • Apply animation to view. 

Load animation 
    Use the below piece of code to load xml. 
               Animation mLeftIn = AnimationUtils.loadAnimation(thisandroid.R.anim.left_in); 

Add AnimationListener 
     Better implement the Animation listener interface with your activity.Then add listener like this 
               mLeftIn.setAnimationListener(this); 

Apply Animation to view: 
     This is as simple as this 
             view.startAnimation(mLeftIn); 

And if you want to do certain actions while animations are playing, you can look into onAnimationStart(), onAnimationEnd() methods in AnimationListener. 
Our animation will play once executed with the code mentioned above. :) 

Other animations can be found below 

Right-in: 

<set xmlns:android="http://schemas.android.com/apk/res/android" > <translate android:duration="@android:integer/config_mediumAnimTime" android:fromXDelta="50%p" android:toXDelta="0" /> <alpha android:duration="@android:integer/config_mediumAnimTime" android:fromAlpha="0.0" android:toAlpha="1.0" /> </set> 

Right-out: 

<
set xmlns:android="http://schemas.android.com/apk/res/android" > <translate android:duration="@android:integer/config_mediumAnimTime" android:fromXDelta="0%p" android:toXDelta="50%p" /> <alpha android:duration="@android:integer/config_mediumAnimTime" android:fromAlpha="1.0" android:toAlpha="0.0" /> </set> 

Top-In: 

<set xmlns:android="http://schemas.android.com/apk/res/android" > <translate android:duration="@android:integer/config_mediumAnimTime" android:fromYDelta="-50%" android:toYDelta="0%" /> <alpha android:duration="@android:integer/config_mediumAnimTime" android:fromAlpha="0.0" android:toAlpha="1.0" /> </set> 

Top-out: 

<set xmlns:android="http://schemas.android.com/apk/res/android" > <translate android:duration="@string/anim_duration" android:fromYDelta="50%p" android:toYDelta="0%p" /> <alpha android:duration="@android:integer/config_mediumAnimTime" android:fromAlpha="1.0" android:toAlpha="0.0" /> </set> 

Bottom-in: 

<set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:duration="@android:integer/config_mediumAnimTime" android:fromYDelta="50%" android:toYDelta="0%" /> <alpha android:duration="@android:integer/config_mediumAnimTime" android:fromAlpha="0.0" android:toAlpha="1.0" /> </set> 

Bottom-Out: 

<set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@android:anim/linear_interpolator" > <translate android:duration="@string/anim_duration" android:fromYDelta="0%" android:toYDelta="100%" /> <alpha android:duration="@android:integer/config_mediumAnimTime" android:fromAlpha="1.0" android:toAlpha="0.0" /> </set> 

This are some of the basic animations. 

Tuesday, February 26, 2013

BB 10 - Logging in Cpp and QML

We can print logs in BB 10 using Cpp and QML.


  •   LOGS in Cpp
    • Using cout
std::cout << "My First LOG" << std::endl;
    • Using fprintf
fprintf(stdout,"%s\n","My first log");
 fflush(stdout);
 You can view these Logs directly in the console window of eclipse.
  •  LOGS in QML
    • We have two ways to print logs in QML via console.log() or console.debug()
console.log("onClicked called..................");

We can view the logs of QML via Terminal. For more details to launch terminal, refer the point's listed below.

  1. In the IDE, in the Target Navigator view, right-click the device target.
  2. Click Launch SSH Session.
  3. To view real-time output for the processes that are being debugged (for applications that are running in development mode), type slog2info -w.
You can also access the log files directly in the /tmp/slogger22 on the device and run these logs through slog2info at a later time.




Tuesday, May 1, 2012

Android loading and Scaling bitmaps


Android provides some methods which directly loads,scales bitmap to the application.But they have their own disadvantages.They are:
  • BitmapFactory.decodeFile(filePath);
    • This method will decode the image from the specified file path.But this causes some problems like 'Skia-->bitmap retuning null' ,which means application is not able to decode the image file due to memory constraints.
  • Bitmap.createScaledBitmap(bitmap,width, height, true);
    • This method will return a scaled bitmap  with the specified width and height. There is a possibility for the method to return null if application heap is not allowing the image to scale to specified dimensions.
This tutorial helps you to load and scale a bitmaps effectively from disk  in android.

The code below first loads and scales image directly using the methods BitmapFactory.decodeFile() and Bitmap.createScaledBitmap(). If image retrieval is failed by using both of the above methods then go for scaling bitmap using BitmapOptions.
 
 
 /**
     *  Scales the Image in originalFilePath to thumbImagePath ,
     *   Saves the scaled Thumbnail Image. 
     * @param originalFilePath    Path where the Original non scaled image exist
     * @param thumbImagePath    Path in which scaled Thumbnail image is saved.
     */
    private void scaleToThumbNail(String originalFilePath,String thumbImagePath) {
       
        FileOutputStream fos = null;
        FileInputStream fis = null;
        boolean isScaled = false;
       
        try{
           
            //   height of image in px which is defined as 90dp in layout. 
            int heightPX = (int)convertDpToPixel(90, _context);
           
            int IMAGE_MAX_SIZE = heightPX;            //px value
           
            Bitmap bitmap = BitmapFactory.decodeFile(originalFilePath);
            int width = 0;
            int height = 0;
            if(bitmap != null)
            {    // bitmap created from file.
                width  = bitmap.getWidth();
                height = bitmap.getHeight();
               
        //    Calculate width and height maintaining aspect ratio.
                if(width &lt; height)
        {   
                    width = (int)(width*((float)IMAGE_MAX_SIZE/height));
                    height = IMAGE_MAX_SIZE;
                   
                }else{
                    height = (int)(height*((float)IMAGE_MAX_SIZE/width));
                    width = IMAGE_MAX_SIZE;
                }
                try{
                    bitmap = Bitmap.createScaledBitmap(bitmap,width, height, true);
                }catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
            }
           
           if(bitmap != null)
            {    // bitmap scaled succesfully
                fos = new FileOutputStream(thumbImagePath);
                isScaled = bitmap.compress(CompressFormat.PNG, 100, fos);
               
               //    Close File OutputStream
                              
            }
           if(!isScaled)
            {    // Unable to scale the image either in createScaledBitmap or  bitmap.compress
               
                //  Caculate the height and width of the decode stream without 
                //  actually decoding into memory.
                BitmapFactory.Options o = new BitmapFactory.Options();
                o.inJustDecodeBounds = true;
                fis = new FileInputStream(originalFilePath);
                BitmapFactory.decodeStream(fis, null, o);
              
               //Close File InputStream here.
              
               
                int scale = 1;
                if (o.outHeight &gt; IMAGE_MAX_SIZE || o.outWidth &gt; IMAGE_MAX_SIZE)
                {    // Calculating scale based in outHeight and outWidth of BitmapOptions.
                    scale = (int)Math.pow(2, (int) Math.round(Math.log(IMAGE_MAX_SIZE 
                            / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
                }

                //  The actual decoding done here using inSampleSize property.
                //  Apply the above calculated scale value to inSampleSize of 
                //  Bitmap Factory Options.
                BitmapFactory.Options o2 = new BitmapFactory.Options();
                o2.inSampleSize = scale;
                fis = new FileInputStream(originalFilePath);
                bitmap = BitmapFactory.decodeStream(fis, null, o2);
               
                // Write the ThumbNail to thumbImagePath
                fos = new FileOutputStream(thumbImagePath);
                bitmap.compress(CompressFormat.PNG, 0, fos);
            }
         
            isScaled= true;
        }catch (Throwable e) {
            // TODO: handle exception
             e.printStackTrace();
        }finally{
        // close all streams.
        }
           
    }

Converting dip to px code which is used in above code snippet is posted below.

        
 /**
  * This method convets dp unit to equivalent device specific value in pixels. 
  * 
  * @param dp A value in dp(Device independent pixels) unit. Which we need to convert into pixels
  * @param context Context to get resources and device specific display metrics
  * @return A float value to represent Pixels equivalent to dp according to device
  */
 public static float convertDpToPixel(float dp,Context context){
     Resources resources = context.getResources();
     DisplayMetrics metrics = resources.getDisplayMetrics();
     float px = dp * (metrics.densityDpi/160f);
     return px;
 }


Hope this tutorial helps out.Any better ides invited.