简体   繁体   中英

Cropping image using createbitmap and a view

I have a view that can be dragged anywhere on the screen, so if a user drags it on the screen. Then everything within the view will only be cropped, how would I be able to achieve that?

I have been able to crop by just calculating which part to crop, but what if I want to crop anything that is within the bounds of the View?

This is my Actiivty:

  View views;

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

    btnCrop = (Button) findViewById(R.id.btnCrop);

    imageView = (ImageView) findViewById(R.id.imageView);

    views = (View) findViewById(R.id.view);

    views.setOnTouchListener(new View.OnTouchListener() {
        private int initialX;
        private int initialY;
        private float initialTouchX;
        private float initialTouchY;
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    initialX = (int) views.getX();
                    initialY = (int) views.getY();
                    initialTouchX = event.getRawX();
                    initialTouchY = event.getRawY();
                    return true;
                case MotionEvent.ACTION_MOVE:
                    views.setX(initialX + (int) (event.getRawX() - initialTouchX));
                    views.setY(initialY + (int) (event.getRawY() - initialTouchY));
                    return true;
            }
            return false;
        }
    });

btnCrop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Bitmap croppedBmp = Bitmap.createBitmap(mbitmap, 0, 0,
                    mbitmap.getWidth(), mbitmap.getHeight() / 2);

            imageView.setImageBitmap(croppedBmp);
        }
    });
   }


public Bitmap getBitmapOFRootView(View v) {
    View screenView = v.getRootView();
    screenView.setDrawingCacheEnabled(true);
    Bitmap bitmap = Bitmap.createBitmap(screenView.getDrawingCache());
    screenView.setDrawingCacheEnabled(false);

    return bitmap;
}

Thanks in advance for any help and insight on what can be done! :D

You don't actually have to reinvent the wheel, there are available libraries for this such as https://github.com/ArthurHub/Android-Image-Cropper and https://github.com/Yalantis/uCrop .

Though, if you would like to study how they did it the codes there are opensource. Check them out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM