Skip to content

Instantly share code, notes, and snippets.

@marcherdiego
Created August 4, 2021 20:47
Show Gist options
  • Save marcherdiego/28cf1add8104bd94dacdf68aecec6d99 to your computer and use it in GitHub Desktop.
Save marcherdiego/28cf1add8104bd94dacdf68aecec6d99 to your computer and use it in GitHub Desktop.
ListView to file
public Bitmap getWholeListViewItemsToBitmap(ListView listview) {
ListAdapter adapter = listview.getAdapter();
int itemCount = adapter.getCount();
int allItemsHeight = 0;
List<Bitmap> bitmaps = new ArrayList<>();
for (int i = 0; i < itemCount; i++) {
View childView = adapter.getView(i, null, listview);
childView.measure(
MeasureSpec.makeMeasureSpec(listview.getWidth(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)
);
childView.layout(0, 0, childView.getMeasuredWidth(), childView.getMeasuredHeight());
childView.setDrawingCacheEnabled(true);
childView.buildDrawingCache();
bitmaps.add(childView.getDrawingCache());
allItemsHeight += childView.getMeasuredHeight();
}
Bitmap bigBitmap = Bitmap.createBitmap(listview.getMeasuredWidth(), allItemsHeight, Bitmap.Config.ARGB_8888);
Canvas bigCanvas = new Canvas(bigBitmap);
Paint paint = new Paint();
int height = 0;
for (int i = 0; i < bitmaps.size(); i++) {
Bitmap bmp = setBackground(bitmaps.get(i));
bigCanvas.drawBitmap(bmp, 0, height, paint);
height += bmp.getHeight();
bmp.recycle();
}
try {
FileOutputStream fileOutputStream = new FileOutputStream(
new File(
new ContextWrapper(getApplicationContext()).getDir("imageDir", Context.MODE_PRIVATE),
"coso" + System.currentTimeMillis() + ".png"
)
);
bigBitmap.compress(CompressFormat.PNG, 100, fileOutputStream);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bigBitmap;
}
private Bitmap setBackground(Bitmap bmp1) {
Bitmap overlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
Bitmap background = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
new Canvas(background).drawColor(getUjetStyle().getPrimaryBackgroundColor());
Canvas canvas = new Canvas(overlay);
canvas.drawBitmap(background, new Matrix(), null);
canvas.drawBitmap(bmp1, new Matrix(), null);
return overlay;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment