Translate

Saturday, February 2, 2013

Rotate an Image using Bitmap

I've tried to findout the solution to tilt the Image for 45 degree .I found in a few minutes. Here is one of the way we can do, In XML create your Imageview and set your desired attributes as shown below, and then our Java file will be ,
public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       /* this.requestWindowFeature(Window.FEATURE_NO_TITLE); */
        setContentView(R.layout.activity_main);
        ImageView im=(ImageView)findViewById(R.id.imageButton1);
      /*  this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);*/
 im.setImageDrawable(rotateImage(this));
    }

    public  Drawable rotateImage(Context ctx) {
        // load the origial Bitmap
        Bitmap BitmapOrg = BitmapFactory.decodeResource(ctx.getResources(),
                R.drawable.vijay);



        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = 90;
        int newHeight = newWidth * height / width;

        // calculate the scale
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        // create a matrix for the manipulation
        Matrix matrix = new Matrix();
        // resize the Bitmap
        matrix.postScale(scaleWidth, scaleHeight);
        // if you want to rotate the Bitmap
        matrix.postRotate(-45);

        // recreate the new Bitmap
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0,
                                                   width, height, matrix, true);

        // make a Drawable from Bitmap to allow to set the Bitmap
        // to the ImageView, ImageButton or what ever
        return new BitmapDrawable(resizedBitmap);

      }
}
Implement these snippets wherever you want in your app :) Need Full source code ? Click Here

No comments:

Post a Comment