Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animating bitmap image in android

I have created a bitmap image which is a circle and than as I wanted to animate it so i converted it into bitmapdrawable and than added it to animation drawable..But due to this the circle shaped has changed to oval shape...

So what should I do ?

Is there any other method to animate only the bitmap file. ?

Thanks in advance..

like image 253
aagam94 Avatar asked Jul 31 '26 19:07

aagam94


1 Answers

If you're using Canvas, I'd suggest holding a pointer to the current Bitmap and loading all other Bitmaps into an array.

Say,

Bitmap[] frames = new Bitmap[10] //10 frames
Bitmap frame[0] = BitmapFactory.decodeResource(getResources(), R.drawable.circlefram1);
Bitmap frame[1] = BitmapFactory.decodeResource(getResources(), R.drawable.circlefram2);
...

Select the currentFrame by pointing at the frame you're interested in.

Bitmap currentBitmap = frame[3]; // 4th frame

So when you call drawBitmap(currentBitmap) it will only draw the frame you are interested in. You can change the bitmap every so many frames, by assigning an fps to the frame animation.

If you just want to scale or rotate the bitmap (rotating a circle?), the best way to resize a bitmap is using createScaledBitmap, and rotating using a matrix.

For Scaling, you load any bitmap into memory like this

Bitmap circleBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.circle);

If you would like the circle (or any bitmap) rescaled you would do something like this:

Bitmap scaledCircle = Bitmap.createScaledBitmap(circleBitmap, dstWidth, dstHeight, filter);

Where dstWidth and dstHeight are the target destination width and height, which you can previously calculate by scaling the original width and height.

int scaledHeight = circleBitmap.getHeight()/2;
int scaledWidth = circleBitmap.getWidth()/2;

And finally you would normally draw this Bitmap using a canvas like this

canvas.drawBitmap(bitmap)

For rotating, create a Matrix

Matrix mat;
mat.postRotate(degrees); // Rotate the matrix
Bitmap rotatedBitmap = Bitmap.createBitmap(originalBitmap, x, y, width, height, mat, filter);

and finally

canvas.drawBitmap(rotatedBitmap);

Keep in mind Canvases are slow for games or anything real-time!

Hope it helps.

like image 186
RedOrav Avatar answered Aug 02 '26 08:08

RedOrav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!