Bitmap из ScrollView преобразует только видимый контент (Android) - PullRequest
0 голосов
/ 25 мая 2020

Я пытаюсь создать растровое изображение из ScrollView. Но он берет только видимое содержимое ScrollView и создает пустое пространство для невидимого. Дополнительно обрезается правый край. Я использовал пример отсюда: Как преобразовать весь контент в режиме прокрутки в растровое изображение?

Manual Screenshot and ScrollView to Bitmap

XML:

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com    /apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.ActivityShowRecipe">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar_showRecipe"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorMidnightBlueLight"
        app:layout_scrollFlags="scroll|enterAlways"
        android:theme="@style/AppTheme.AppBarOverlay"
        app:popupTheme="@style/AppTheme.PopupOverlay"
        tools:ignore="MissingConstraints">

        <TextView
            android:id="@+id/toolbarShowRecipe_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/white"
            android:fontFamily="@font/indie_flower"
            android:textSize="30sp"
            android:layout_gravity="left"
            />
    </androidx.appcompat.widget.Toolbar>

    <ScrollView
        android:id="@+id/scrollview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="0dp"
        >
        <LinearLayout
            android:layout_width="match_parent"
            android:orientation="vertical"
            android:layout_height="wrap_content"
            tools:ignore="MissingConstraints">

            <TextView
                android:id="@+id/textViewTitle"
                android:layout_marginTop="20dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginEnd="8dp"
                android:fontFamily="@font/indie_flower"
                android:textAlignment="center"
                android:textSize="30sp">
            </TextView>
            <TextView
                android:id="@+id/textViewDuration"
                android:layout_marginBottom="20dp"
                android:layout_marginStart="8dp"
                android:layout_marginEnd="8dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="@font/indie_flower"
                android:textSize="20sp"
                android:textAlignment="center"
                android:maxLines="1" />
            <ImageView
                android:id="@+id/RecipeImage"
                android:adjustViewBounds="true"
                android:scaleType="fitCenter"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="0dp"
                android:layout_marginTop="10dp"
                android:paddingTop="0dp"
                android:paddingBottom="0dp"
                android:paddingRight="10dp"
                android:layout_gravity="center"
                android:src="@drawable/food"/>
            <RatingBar
                android:id="@+id/Ratingstars"
                android:layout_width="wrap_content"
                style="?android:attr/ratingBarStyleIndicator"
                android:layout_gravity="center"
                android:layout_marginTop="15dp"
                android:layout_marginBottom="15dp"
                android:theme="@style/RatingBar"
                android:layout_height="wrap_content">
            </RatingBar>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginRight="10dp"
                    android:layout_marginBottom="20dp"
                    android:orientation="vertical">
                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:textSize="20sp"
                        android:text="@string/ActivityShowRecipe_lbl_Incredients"/>
                    <View
                        android:layout_width="match_parent"
                        android:layout_height="1dp"
                        android:layout_marginBottom="10dp"
                        android:background="@color/colorLightGrey"
                        />
                    <TextView
                        android:id="@+id/textViewIngredients"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:textSize="15sp"
                        />
                </LinearLayout>


            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_marginBottom="20dp"
                android:orientation="vertical">
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="20sp"
                    android:text="@string/ActivityShowRecipe_lbl_Recipe"/>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:layout_marginBottom="10dp"
                    android:background="@color/colorLightGrey"
                    />
                <TextView
                    android:id="@+id/textViewRecipe"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="15sp"
                    />
            </LinearLayout>



            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:orientation="vertical">
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="20sp"
                    android:text="@string/ActivityShowRecipe_lbl_Annotation"/>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:layout_marginBottom="10dp"
                    android:background="@color/colorLightGrey"
                    />
                <TextView
                    android:id="@+id/textViewAnnotation"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="15sp"
                    />
            </LinearLayout>
        </LinearLayout>

    </ScrollView>




</androidx.constraintlayout.widget.ConstraintLayout>

java (код снимка экрана):

private void takeScreenShot()
{
    View u = ((Activity) this).findViewById(R.id.scrollview);

    ScrollView z = (ScrollView) ((Activity) this).findViewById(R.id.scrollview);
    int totalHeight = z.getChildAt(0).getHeight();
    int totalWidth = z.getChildAt(0).getWidth();

    Bitmap image = getBitmapFromView(u,totalHeight,totalWidth);

    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("image/jpeg");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String pathname = Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg";
    File f = new File(pathname);
    try {
        f.createNewFile();
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
    } catch (IOException e) {
        e.printStackTrace();
    }
    share.putExtra(Intent.EXTRA_STREAM, Uri.parse(pathname));
    startActivity(Intent.createChooser(share, "Share Image"));

}

public Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) {

    Bitmap returnedBitmap = Bitmap.createBitmap(totalWidth,totalHeight , Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(returnedBitmap);
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        bgDrawable.draw(canvas);
    else
        canvas.drawColor(Color.WHITE);
    view.draw(canvas);
    return returnedBitmap;
}

java (полный код):

public class ActivityShowRecipe extends AppCompatActivity {
Integer ID;
HandlerDatabase dbhandler;
static TextView Toolbartitle;

static ActivityShowRecipe activityShowRecipe;
Bitmap bitmap;
DialogInterface.OnClickListener dialogClickListener;
TextView textViewTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_show_recipe);
   // this.getSupportActionBar().hide();

    activityShowRecipe = this;

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_showRecipe);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);
    Toolbartitle = findViewById(R.id.toolbarShowRecipe_title);
    Toolbartitle.setText(R.string.ActivityShowRecipe_ToolbarTitle);

    dbhandler = new HandlerDatabase(this);

    Bundle extras = getIntent().getExtras();
    if(extras == null) {
        ID = 1;
    } else {
        ID = extras.getInt("ID");
    }

    dialogClickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which){
                case DialogInterface.BUTTON_POSITIVE:
                    //Yes button clicked
                    deleteRecipe();
                    break;

                case DialogInterface.BUTTON_NEGATIVE:
                    //No button clicked
                    break;
            }
        }
    };



    String title = dbhandler.loadData(HandlerDatabase.RECIPES_TITLE, HandlerDatabase.TABLE_NAME_RECIPES, HandlerDatabase._ID, Integer.toString(ID));
    textViewTitle = (TextView) findViewById(R.id.textViewTitle);
    textViewTitle.setText(title);

    String duration = dbhandler.loadData(HandlerDatabase.RECIPES_DURATION, HandlerDatabase.TABLE_NAME_RECIPES, HandlerDatabase._ID, Integer.toString(ID));
    TextView textViewDuration = (TextView) findViewById(R.id.textViewDuration);
    textViewDuration.setText(getString(R.string.Overview_Duration) + ": " + duration + " min");

    Bitmap image = dbhandler.loadImage(HandlerDatabase.RECIPES_IMAGE, HandlerDatabase.TABLE_NAME_RECIPES, HandlerDatabase._ID, Integer.toString(ID));
    ImageView imageview = (ImageView) findViewById(R.id.RecipeImage);
    imageview.setImageBitmap(image);

    String rating = dbhandler.loadData(HandlerDatabase.RECIPES_RATING, HandlerDatabase.TABLE_NAME_RECIPES, HandlerDatabase._ID, Integer.toString(ID));
    RatingBar ratingbar = findViewById(R.id.Ratingstars);
    ratingbar.setRating(Float.parseFloat(rating));

    String incredients = dbhandler.loadData(HandlerDatabase.RECIPES_INCREDIENTS, HandlerDatabase.TABLE_NAME_RECIPES, HandlerDatabase._ID, Integer.toString(ID));
    TextView textViewIncredients = findViewById(R.id.textViewIngredients);
    textViewIncredients.setText(incredients);

    String recipe = dbhandler.loadData(HandlerDatabase.RECIPES_RECIPE, HandlerDatabase.TABLE_NAME_RECIPES, HandlerDatabase._ID, Integer.toString(ID));
    TextView textViewRecipe = findViewById(R.id.textViewRecipe);
    textViewRecipe.setText(recipe);

    String annotations = dbhandler.loadData(HandlerDatabase.RECIPES_ANNOTATION, HandlerDatabase.TABLE_NAME_RECIPES, HandlerDatabase._ID, Integer.toString(ID));
    TextView textViewAnnotations = findViewById(R.id.textViewAnnotation);
    textViewAnnotations.setText(annotations);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_showrecipe, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.item_delete) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(getText(R.string.dialog_delete).toString()).setPositiveButton(getText(R.string.dialog_yes).toString(), dialogClickListener)
                .setNegativeButton(getText(R.string.dialog_no).toString(), dialogClickListener).show();

    }else if(id == R.id.item_edit){
        MainActivity.getInstance().initiateEditingFromShowRecipeActivity(ID);
    }else if(id == R.id.item_share){
        takeScreenShot();
    }else if(id == R.id.item_note_recipe){
        Intent intent = new Intent(android.content.Intent.ACTION_SEND);
        String shareBody = dbhandler.loadData(HandlerDatabase.RECIPES_INCREDIENTS, HandlerDatabase.TABLE_NAME_RECIPES, HandlerDatabase._ID, Integer.toString(ID));
        intent.setType("text/plain");
        intent.putExtra(android.content.Intent.EXTRA_SUBJECT, dbhandler.loadData(HandlerDatabase.RECIPES_TITLE, HandlerDatabase.TABLE_NAME_RECIPES, HandlerDatabase._ID, Integer.toString(ID)));
        intent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        startActivity(Intent.createChooser(intent, getString(R.string.save_incredients)));
    }

    return super.onOptionsItemSelected(item);
}

void deleteRecipe(){
    dbhandler.deleteFromTableWhereValueIs(dbhandler._ID,ID);
    OverviewFragment.getInstance().updateAdapters();
    finish();
}
public static ActivityShowRecipe getInstance(){
    return   activityShowRecipe;
}



private void takeScreenShot()
{
    View u = ((Activity) this).findViewById(R.id.scrollview);

    ScrollView z = (ScrollView) ((Activity) this).findViewById(R.id.scrollview);
    int totalHeight = z.getChildAt(0).getHeight();
    int totalWidth = z.getChildAt(0).getWidth();

    Bitmap image = getBitmapFromView(u,totalHeight,totalWidth);

    Intent share = new Intent(Intent.ACTION_SEND);
    share.setType("image/jpeg");
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String pathname = Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg";
    File f = new File(pathname);
    try {
        f.createNewFile();
        FileOutputStream fo = new FileOutputStream(f);
        fo.write(bytes.toByteArray());
    } catch (IOException e) {
        e.printStackTrace();
    }
    share.putExtra(Intent.EXTRA_STREAM, Uri.parse(pathname));
    startActivity(Intent.createChooser(share, "Share Image"));

}

public Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) {

    Bitmap returnedBitmap = Bitmap.createBitmap(totalWidth,totalHeight , Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(returnedBitmap);
    Drawable bgDrawable = view.getBackground();
    if (bgDrawable != null)
        bgDrawable.draw(canvas);
    else
        canvas.drawColor(Color.WHITE);
    view.draw(canvas);
    return returnedBitmap;
}
}
...