mardi 12 mai 2015

Create bitmap from two imageView with exact location

My Target:

  • Get one photo from camera or gallery, then set it to imageViewA
  • Add a draggable mask imageViewB on top of imageViewA
  • Users drag the mask imageViewB to anywhere in imageViewA
  • Users then click the save button
  • A combined bitmap of imageViewA and imageViewB should be created

My Problem:

Everything works fine, except that the imageViewB in the combined bitmap is not positioned appropriately (see the attached picture) enter image description here

Code (MainActivity.java):

public class MainActivity extends ActionBarActivity {
Bitmap bmMask = null;
Bitmap bmOriginal =  null;
Bitmap bmCombined = null;

ImageView normalImgView;
ImageView maskImgView;
ImageView combinedImgView;

static final int REQUEST_TAKE_PHOTO = 55;
static final int REQUEST_LOAD_IMAGE = 60;
String currentImagePath;
static final String TAG = "mover";

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

    combinedImgView = (ImageView) findViewById(R.id.combinedImgView);
    normalImgView = (ImageView) findViewById(R.id.normalImgView);

    maskImgView = (ImageView) findViewById(R.id.maskImgView);
    bmMask = ((BitmapDrawable) maskImgView.getDrawable()).getBitmap();


    Button addBtn = (Button) findViewById(R.id.addBtn);
    addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            bmCombined = ProcessingBitmap();
            if(bmCombined!=null){
                combinedImgView.setImageBitmap(bmCombined);
            }
            else {
                Log.d(MainActivity.TAG, "combined bm is null");
            }
        }
    });

    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.d(MainActivity.TAG, "clicked");
            getImageFromCameraIntent();
        }
    });

    MultiTouchListener mTouchListener = new MultiTouchListener();
    mTouchListener.isRotateEnabled = false;
   //        mTouchListener.isTranslateEnabled = false;
    mTouchListener.isScaleEnabled = false;
    maskImgView.setOnTouchListener(mTouchListener);
}

// take image from camera
private void getImageFromGalleryIntent() {
    Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, REQUEST_LOAD_IMAGE);
}

// take image from camera
private void getImageFromCameraIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(this.getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

// create a image file for storing full size image taken from camera
private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = timeStamp + "_";
    File storageDir = Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    currentImagePath = image.getAbsolutePath();
    Log.d(MainActivity.TAG, "photo path: " + currentImagePath);

    return image;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
        // photo returned from camera
        // update UI
        updatePhotoView(currentImagePath);

    } else if (requestCode == REQUEST_LOAD_IMAGE && resultCode == Activity.RESULT_OK) {
        // photo returned from gallery
        // update UI
        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = this.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        updatePhotoView(picturePath);

    } else {
        Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
    }
}

// scale down the image, then display it to image view
private void updatePhotoView(String photoPath) {


    // Get the dimensions of the bitmap
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(photoPath, bmOptions);


    // Decode the image file into a Bitmap sized to fill the View
    bmOptions.inJustDecodeBounds = false;
    bmOptions.inPurgeable = true;

    Bitmap bitmap = BitmapFactory.decodeFile(photoPath, bmOptions);
    bmOriginal = bitmap;
    normalImgView.setImageBitmap(bmOriginal);
}

private Bitmap ProcessingBitmap(){

    Bitmap newBitmap = null;

    int w;
    w = bmOriginal.getWidth();

    int h;
    h = bmOriginal.getHeight();

    Bitmap.Config config = bmOriginal.getConfig();
    if(config == null){
        config = Bitmap.Config.ARGB_8888;
    }

    newBitmap = Bitmap.createBitmap(w, h, config);
    Canvas newCanvas = new Canvas(newBitmap);

    newCanvas.drawBitmap(bmOriginal, 0, 0, null);

    Paint paint = new Paint();

    float left = maskImgView.getLeft();
    float top = maskImgView.getTop();
    Log.d(MainActivity.TAG, "left is " + left);
    Log.d(MainActivity.TAG, "top is " + top);

    newCanvas.drawBitmap(bmMask, left, top, paint);

    return newBitmap;
}
}

Code (xml)

<RelativeLayout
    android:id="@+id/imgSection"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="5"
    android:background="@android:color/background_dark">

    <TextView
        android:id="@+id/before_combie_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="before combine image"
        android:textColor="@android:color/white"/>

        <ImageView
            android:id="@+id/normalImgView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <ImageView
            android:id="@+id/maskImgView"
            android:layout_centerInParent="true"
            android:src="@drawable/daffodils"
            android:layout_width="100dp"
            android:layout_height="60dp" />

</RelativeLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="5"
    android:background="@android:color/holo_blue_dark">
    <TextView
        android:id="@+id/after_combie_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="after combine image"
        android:textColor="@android:color/white"/>
    <ImageView
        android:id="@+id/combinedImgView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>


<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1"
    android:text="Take Photo"
    android:layout_gravity="center_horizontal"/>

<Button
    android:id="@+id/addBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Get Combined Photo"
    android:layout_gravity="center_horizontal"/>

My Thought:

I guess the positioning issue occurs in the few lines of code listed below. I just have no idea how to get it right, yet.

        float left = maskImgView.getLeft();
        float top = maskImgView.getTop();
        newCanvas.drawBitmap(bmMask, left, top, paint);

Any help is appreciated!

Aucun commentaire:

Enregistrer un commentaire