Alternative to Drawing

One of the drawbacks to the methods we are using in the foregoing sections is that the images get cut off, as we aren't calculating the resulting size after the transformation and just drawing into a Bitmap with a predetermined size.

One way that we can overcome this issue is to apply the Matrix as we are creating the Bitmap in the first place, rather than drawing into an empty Bitmap.

Going about things this way removes the need for us to have a Canvas and a Paint object. The drawback is that we cannot continually change the Bitmap object and have to recreate it if we want to do any more transformations on it.

The static createBitmap method available in the Bitmap class allows this. The first argument is the source Bitmap, the next arguments are the start x, y, width, and height values to use from the source, followed by the Matrix to apply, and last a Boolean representing whether to apply any filtering to the image. Since we are not applying a matrix that contains a filter, which we'll discuss later in the chapter, we set that to be false.

Matrix matrix = new Matrix();

matrix.setRotate(15,bmp.getWidth()/2,bmp.getHeight()/2);

alteredBitmap = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeightQ,^ matrix, false);

alteredImageView.setImageBitmap(alteredBitmap);

As you can see, we deal with the matrix in the same way, but we instantiate our second Bitmap (alteredBitmap) using the original (bmp) as the source and pass in the Matrix object. This creates a Bitmap from the source with the translation and scaled to the size of the Bitmap object as shown in Figure 3-14.

Choose Picture

Choose Picture iîr

Figure 3-14. Matrix applied when Bitmap created; the dimensions of the Bitmap are adjusted to match the actual image data.

Was this article helpful?

0 0

Post a comment