Crop a Bitmap image
I used this method to crop the image and it works perfect:
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.xyz);
Bitmap resizedBmp = Bitmap.createBitmap(bmp, 0, 0, yourwidth, yourheight);
createBitmap()
takes bitmap
, start X
, start Y
, width
& height
as parameters.
Using the answer above does not work if you want to slice/crop areas particular out of bounds! Using this code you will always get your desired size - even if the source is smaller.
// Here I want to slice a piece "out of bounds" starting at -50, -25
// Given an endposition of 150, 75 you will get a result of 200x100px
Rect rect = new Rect(-50, -25, 150, 75);
// Be sure that there is at least 1px to slice.
assert(rect.left < rect.right && rect.top < rect.bottom);
// Create our resulting image (150--50),(75--25) = 200x100px
Bitmap resultBmp = Bitmap.createBitmap(rect.right-rect.left, rect.bottom-rect.top, Bitmap.Config.ARGB_8888);
// draw source bitmap into resulting image at given position:
new Canvas(resultBmp).drawBitmap(bmp, -rect.left, -rect.top, null);
...and you're done!