简体   繁体   中英

Create image of part of an other image

I'm trying to draw a sprite sheet animation on the screen this worked fine before when I was using this code.

    canvas.drawColor(Color.TRANSPARENT);
    Rect src = new Rect(CurrentSprite.x * SheetSize.x, CurrentSprite.y * SheetSize.y, (CurrentSprite.x * SheetSize.x) + SheetSize.x, (CurrentSprite.y * SheetSize.y) + SheetSize.y);
    Rect dst = new Rect(X, Y, X + SheetSize.x, Y + SheetSize.y);
    canvas.drawBitmap(bmp, src, dst, null);

However I now need to rotate the image before I draw it on the screen. So I changed the code so I'm making a local copy of the sprite. I'm going to draw this is however here I get a problem. I'm using the Bitmap.createBitmap method but it seems this method does nothing because when I look at the screen the complete sprite sheet is drawn on the screen and sometimes I'm getting OutOfMemoryException (understandable because the full image is quite large).

    canvas.drawColor(Color.TRANSPARENT);
    Matrix matrix = new Matrix();
    matrix.postRotate(Degrees);
    Bitmap tempAnimationBmp = Bitmap.createBitmap(bmp, CurrentSprite.x * SheetSize.x, CurrentSprite.y * SheetSize.y, (CurrentSprite.x * SheetSize.x) + SheetSize.x, (CurrentSprite.y * SheetSize.y) + SheetSize.y, matrix, true);
    canvas.drawBitmap(tempAnimationBmp, X, Y, null);
    tempAnimationBmp.recycle();

Why do I get the full sprite sheet?

I'd recommend using one of the DrawableContainer s instead of trying to create a bunch of bitmaps. Drawables are really easy to use - you just set the dimensions, pass it a canvas and it'll draw itself to the canvas at that location. The great thing about Drawables is that they're also very easy to make, so you could create a custom SpriteDrawable class which takes a resource from the system and only draws regions of it to the canvas.

By working on this flow instead of trying to create a bunch of bitmaps you'll save a ton of memory and probably a lot of headache as you try to work more with Android's graphics system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM