在Android中裁剪拖动区域

时间:2013-10-31 06:00:39

标签: android bitmap android-canvas

我在图像视图中设置了位图。当我触摸位图的一个点并拖动到另一个点时,我想将拖动的区域提取到另一个位图中。

经过一些谷歌搜索后,我发现Canvas必须在这种情况下使用。我怎么能完成它?我可以使用以下代码:

@Override
public boolean onTouchEvent (MotionEvent event) {

  if (event.getAction() == MotionEvent.ACTION_DOWN) {

    start_x = event.getX();
    start_y = event.getY();     

  } else if (event.getAction() == MotionEvent.ACTION_MOVE) {

    //create the line from start_x and start_y to the current location
    //don't forget to invalidate the View otherwise your line won't get redrawn

  } else if (event.getAction() == MotionEvent.ACTION_UP) {

    //might not need anything here

  }
  return true;
}

1 个答案:

答案 0 :(得分:0)

我在不使用Canvas的情况下提出了答案,使用onTouch()进行图像视图:

public class Test extends Activity {

    ArrayList<Integer> array_x = new ArrayList<Integer>();
    ArrayList<Integer> array_y = new ArrayList<Integer>();
    Button btnArray;
    Bitmap charscropped;

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

        ImageView img = (ImageView) findViewById(R.id.imageView1);
        final ImageView img2 = (ImageView) findViewById(R.id.imageCroppd);
        img.setImageBitmap(CaptureActivity.staticBitmap);

        btnArray = (Button) findViewById(R.id.btn_for_array);
        btnArray.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                for (int i = 0; i < array_x.size(); i++) {
                    Log.e("Array Index-" + i, " - " + array_x.get(i));
                }

                int xBegin = array_x.get(0);
                int xEnd = array_x.get(array_x.size()-1);
                int yBegin = array_y.get(0);
                int yEnd = array_y.get(array_y.size()-1);
                CaptureActivity.staticBitmap.getWidth();
                CaptureActivity.staticBitmap.getHeight();

                //charscropped = Bitmap.createBitmap(CaptureActivity.staticBitmap, xBegin, yBegin, img2.getWidth(), img2.getHeight());
                charscropped = Bitmap.createBitmap(CaptureActivity.staticBitmap, xBegin, yBegin-20, 200, 40);
                img2.setImageBitmap(charscropped);
            }

        });

        img.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int x = (int) event.getX();
                int y = (int) event.getY();
                array_x.add(x);
                return array_y.add(y);
            }
        });

    }

}