Animating bitmap image in android

2019-04-11 20:45发布

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..

2条回答
SAY GOODBYE
2楼-- · 2019-04-11 21:24

no, you can not animate the bitmap itself with the android animation framwork. You can directly animate Views or ViewGroups and all the classes that derives from View and ViewGroup.

Call view the ImageView that contains the bitmap.

TranslateAnimation slide = new TranslateAnimation(view.getX(), view.getX()  + 100, view.getY(), view.getY()  + 100 );   
slide.setDuration(1000);
view.startAnimation(slide) 

that should translate the ImageView by 100px from the current position

查看更多
迷人小祖宗
3楼-- · 2019-04-11 21:38

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.

查看更多
登录 后发表回答