java - 如何将多个 View 合并到一张位图中

标签 java android

我从用户图库中挑选了一张图像。我还有一个生成自定义编辑文本的按钮,我可以在相对布局周围拖动其值。这部分代码工作正常,但我想知道是否有一种方法可以创建一个位图,捕获屏幕,就像从用户图库中选取该图像、编辑文本值和图像未覆盖的布局的其他部分(我使用中心裁剪比例类型)一样。 正如您在我的 SendToDb 方法中看到的,我已经尝试使用 createBitmap 但这返回一个空值,只是一个空的屏幕布局,既没有图像也没有编辑文本值。关于如何获得包含图像和编辑文本的新位图有什么帮助吗?任何帮助,将不胜感激。谢谢! 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>

在 Activity 中

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()  );
        }
    }
}

最佳答案

如果要将多个 View 绘制到位图上,请调用包含所有 View 的父 View 组的draw方法。

关于java - 如何将多个 View 合并到一张位图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55441593/

相关文章:

java - java中的复合模式

java - 尝试使用 ImageIO.read 加载图像时出错

android - 在 SnackBar 上包装内容高度

android - 如何在没有操作栏的情况下添加菜单按钮?

android - 从模拟器中卸载 Widget

java - Spark 作业无法在 Kubernetes 集群上启动

java - 新的空项目上的 Android Studio org.gradle.api.tasks.TaskExecutionException

android - ARM EABI v7a系统镜像在android中有什么用?

java - 单独线程上的网络相关任务

java - Jersey :找不到媒体类型 = 应用程序/json、类型 = 类 org.codehaus.jackson.node.ObjectNode 的 MessageBodyWriter?