'Can't convert layout to bitmap in Java Android
I'm trying to generate an image for my users to share, to do that I've tried making a ConstraintLayout that basically consists of two TextViews whose values I want to change depending on the situtation.
This is how the layout looks layout
This is what I have tried so far but when I try to share the image its just black which I think is a sign of me not getting the layout I want correctly. Note that the button is being called on a fragment.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_marker_info, container, false);
//trying to get the View needed to convert to image
View inflatedView = getLayoutInflater().inflate(R.layout.share_event_layout, null);
//the two textviews on the layout
TextView organizerName = inflatedView.findViewById(R.id.organizerShareName);
TextView organizerAddress = inflatedView.findViewById(R.id.organizerShareAddress);
Button shareButton = view.findViewById(R.id.shareEventBtn);
shareButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//change their values
organizerName.setText(getArguments().get("name").toString());
organizerAddress.setText(getArguments().get("address").toString());
//converting to image and share
Bitmap icon = getBitmapFromView(inflatedView);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContext().getContentResolver(), icon, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));
}
});
return view;
}
private Bitmap getBitmapFromView(View view) {
//Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(1080, 900,Bitmap.Config.ARGB_8888);
//Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
//Get the view's background
Drawable bgDrawable =view.getBackground();
if (bgDrawable!=null) {
//has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
} else{
//does not have background drawable, then draw white background on the canvas
canvas.drawColor(Color.WHITE);
}
// draw the view on the canvas
view.draw(canvas);
//return the bitmap
return returnedBitmap;
}
Solution 1:[1]
FrameLayout view = (FrameLayout)findViewById(R.id.framelayout);
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bm = view.getDrawingCache();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | John Cvelth |
