Working with Bitmaps Android

You can find lots of goodies for working with graphics such as bitmaps (including NinePatch) in the package. The core class for bitmaps is

Drawing Bitmap Graphics on a Canvas

You can draw bitmaps onto a valid Canvas, such as within the onDraw() method of a View, using one of the drawBitmap() methods. For example, the following code loads a Bitmap resource and draws it on a canvas:

Scaling Bitmap Graphics

Perhaps you want to scale your graphic to a smaller size. In this case, you can use the createScaledBitmap() method, like this:

You can preserve the aspect ratio of the Bitmap by checking the getWidth() and getHeight() methods and scaling appropriately.

Transforming Bitmaps Using Matrixes

You can use the helpful Matrix class to perform transformations on a Bitmap graphic. Use the Matrix class to perform tasks such as mirroring and rotating graphics, among other actions.

The following code uses the createBitmap() method to generate a new Bitmap that is a mirror of an existing Bitmap called pic:

You can perform a 30-degree rotation in addition to mirroring by using this Matrix instead:

You can see the results of different combinations of tilt and mirror Matrix transforms in Figure. When you’re no longer using a Bitmap, you can free its memory using the recycle() method:

A single-source bitmap: scaled, tilted, and mirrored using Android Bitmap classes.

single-source bitmap: scaled, tilted, and mirrored using Android Bitmap classes

There are a variety of other Bitmap effects and utilities available as part of the Android SDK, but they are numerous and beyond the scope of this book. See the package for more details.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Android Topics