Cropping images from a png file in Android
So I’ve never tried to crop single images from a multi-image bitmap ( like these images ), but after some tweeking I ended up with the following code snippet, I’m sure it’s not the only way, but it seems to work out pretty well.
private Drawable getImg( int idx )
{
InputStream is = getResources().openRawResource( R.raw.myicons );
BitmapDrawable bm = new BitmapDrawable( is );
try {
is.close();
} catch (IOException e) { /** noop, stream is closed **/ }
BitmapDrawable img = new BitmapDrawable( Bitmap.createBitmap( bm.getBitmap(), 22 * idx, 0, 22, 22 ) );
img.setBounds( 0, 0, 40, 40 );
return img;
}
Of course, you’ll have to supply your own myicons.png in the /res/raw directory and a corresponding size (mine is 22). You’ll also want to change the code so the BitmapDrawable “bm” is only loaded once, most likely in a constructor, then used multiple times from the above getImg method.
