如何将多个视图合并到一个位图中

时间:2019-03-31 13:50:10

标签: java android

我有一个从用户图库中挑选的图片。我还有一个按钮可以生成自定义的“编辑文本”,我可以将其值拖到相对布局中。这部分代码可以正常工作,但是我想知道是否有一种方法可以创建一个位图来捕获屏幕,就像从用户库中选择此图像,“编辑文本”值和其他部分一样。图片未覆盖的版式(采用中心裁切比例类型)。 如您在我的SendToDb方法中所看到的,我已经尝试使用createBitmap,但是它返回一个空值,只是一个空的屏幕布局,既没有图像也没有编辑文本值。关于如何同时具有图像和edittext的新位图有任何帮助吗?任何帮助,将不胜感激。谢谢! Here is a screenshot of the final bitmap I'd like to have. Thanks in advance!

这是我的xml代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:background="@color/white"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".CanvasTestActivity">


       <RelativeLayout
           android:id="@+id/imgv"
           android:layout_above="@+id/post"
           android:layout_width="match_parent"
           android:layout_height="match_parent"/>


        <ImageButton
            android:id="@+id/select"
            android:layout_width="match_parent"
            android:layout_height="350dp"
            android:scaleType="centerCrop"
            android:layout_alignParentStart="true"
            android:layout_centerVertical="true" />

        <RelativeLayout
            android:id="@+id/drag"
            android:visibility="invisible"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </RelativeLayout>


        <ImageButton
            android:id="@+id/editshow"
            android:visibility="invisible"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_alignParentTop="true"
            android:layout_marginEnd="11dp"
            android:layout_marginTop="200dp"
            android:src="@drawable/ic_bio" />

        <Button
            android:id="@+id/post"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentStart="true"
            android:background="@color/white"
            android:text="Post" />

</RelativeLayout>

和活动中

public class CanvasTestActivity extends AppCompatActivity {

    private Button Post;
    private ImageButton selectStory, showet;
    private RelativeLayout mLayout;

    private EditText userInput;
    private String currentUserId, caption, msg;



    private DatabaseReference PostsRef;
    private StorageReference TestPostStorage;
    private RelativeLayout dragLayout;
    RelativeLayout.LayoutParams params;
    private Uri imageUri;
    Bitmap bm;
    Boolean clicked = false;

    private final static int Gall_pick = 67;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_canvas_test);


        currentUserId = FirebaseAuth.getInstance().getCurrentUser().getUid();



        mLayout = findViewById(R.id.imgv);


        Post = findViewById(R.id.post);
        selectStory = findViewById(R.id.select);
        showet =  findViewById(R.id.editshow);
        showet.setVisibility(View.VISIBLE);
        dragLayout = findViewById(R.id.drag);
        dragLayout.setOnDragListener(new MyDragListener());


        dragLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        int x = (int) motionEvent.getX();
                        int y = (int) motionEvent.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        x = (int) motionEvent.getX();
                        y = (int) motionEvent.getY();
                        break;

                }
                return true;
            }
        });


        PostsRef = FirebaseDatabase.getInstance().getReference().child("CanvasTestPosts");
        TestPostStorage  = FirebaseStorage.getInstance().getReference().child("CTPStorage");

        selectStory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OpenGallere();
            }
        });


       showet.setOnClickListener(new MyButtonClickListener());
       Post.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               SendToDb();
           }
       });



    }

    public class CustomEdittext extends android.support.v7.widget.AppCompatEditText
    {

        Paint paint;

        public CustomEdittext(Context context){
            super(context);
            init();


        }

        public CustomEdittext(Context context, AttributeSet attr){
            super(context, attr);

            init();

        }


        public void init(){


            paint = new Paint();

            paint.setAntiAlias(true);
            paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeWidth(4);
            paint.setTextSize(22);
            paint.setColor(Color.WHITE);


        }

        @Override
        protected void onDraw(Canvas canvas)
        {

            super.onDraw(canvas);

            canvas.drawRect(0, 0, getWidth(), getHeight(), paint);

        }


    }
    public class MyDragListener implements View.OnDragListener
    {

        private RelativeLayout.LayoutParams params;

        @Override
        public boolean onDrag(View v, DragEvent event)
        {
            View view = (View) event.getLocalState();


            switch(event.getAction())
            {
                case DragEvent.ACTION_DRAG_STARTED:

                    params = (RelativeLayout.LayoutParams) view.getLayoutParams();
                    break;

                case DragEvent.ACTION_DRAG_ENTERED:
                    int x = (int) event.getX();
                    int y = (int) event.getY();

                    break;

                case DragEvent.ACTION_DRAG_EXITED :

                    break;

                case DragEvent.ACTION_DRAG_LOCATION  :
                    x=  (int) event.getX();
                    y =  (int) event.getY();
                    break;

                case DragEvent.ACTION_DRAG_ENDED   :

                    break;

                case DragEvent.ACTION_DROP:

                    x = (int) event.getX();
                    y = (int) event.getY();
                    params.leftMargin = x;
                    params.topMargin = y;

                    view.setLayoutParams(params);
                    view.setVisibility(View.VISIBLE);

                    break;
                default: break;
            }
            return true;
        }


    }





    private void SendToDb() {
        final String key = PostsRef.push().getKey();
        StorageReference filePath = TestPostStorage.child(key);


        Bitmap returnedBitmap = Bitmap.createBitmap(mLayout.getWidth(), mLayout.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(returnedBitmap);

        Drawable bgDrawable = mLayout.getBackground();
        if (bgDrawable != null){
            bgDrawable.draw(canvas);


        } else {
            canvas.drawColor(Color.WHITE);
            mLayout.draw(canvas);

        }


        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        returnedBitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
        byte[] dataToUpload = baos.toByteArray();
        UploadTask uploadTask = filePath.putBytes(dataToUpload);

        uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Uri imageUrl = taskSnapshot.getDownloadUrl();

                finish();
                return;

            }
        });



    }



    private void OpenGallere() {
        Intent gIntent = new Intent();
        gIntent.setAction(Intent.ACTION_GET_CONTENT);
        gIntent.setType("image/*");
        startActivityForResult(gIntent, Gall_pick);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Gall_pick && resultCode == RESULT_OK && data != null){
            imageUri = data.getData();

            try {
                bm = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
                selectStory.setImageBitmap(bm);
            } catch (IOException e){
                e.printStackTrace();
            }

        showet.setVisibility(View.VISIBLE);
        dragLayout.setVisibility(View.VISIBLE);

        }
    }

    private class MyLongClickListener implements View.OnLongClickListener {

        @Override
        public boolean onLongClick(View v)
        {

            ClipData dragdata = ClipData.newPlainText("","");

            View.DragShadowBuilder shdwbldr = new View.DragShadowBuilder(v);

            v.startDrag(dragdata, shdwbldr, v, 0);
            v.setVisibility(View.INVISIBLE);

            return true;
        }
    }

    private class MyButtonClickListener implements View.OnClickListener {

        @Override
        public void onClick(View view) {
            ViewGroup rp = (ViewGroup)view.getParent();
            CustomEdittext edttext = new CustomEdittext(view.getContext());
            rp.addView(edttext);
            edttext.setOnLongClickListener(new MyLongClickListener()  );
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果要在一个位图上绘制多个视图,请调用包含所有视图的父viewGroup的draw方法。