从两个imageView创建具有确切位置

时间:2015-05-12 12:47:18

标签: android android-layout bitmap

我的目标:

  • 从相机或图库中获取一张照片,然后将其设置为imageViewA
  • 在imageViewA
  • 上添加可拖动遮罩imageViewB
  • 用户将屏幕imageViewB拖到imageViewA
  • 中的任意位置
  • 然后用户点击保存按钮
  • 应创建imageViewA和imageViewB的组合位图

我的问题:

一切正常,但组合位图中的imageViewB位置不合适(参见附图) enter image description here

代码(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;
}
}

代码(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"/>

我的想法:

我猜定位问题出现在下面列出的几行代码中。我只是不知道如何做到这一点。

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

感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

在这种情况下,两个图像视图都是相同的布局,例如

layoutSubviews()

-------&GT;

class FramedTextField: UITextField {

    @IBInspectable var linesWidth: CGFloat = 1.0 { didSet{ drawLines() } }

    @IBInspectable var linesColor: UIColor = UIColor.blackColor() { didSet{ drawLines() } }

    @IBInspectable var leftLine: Bool = false { didSet{ drawLines() } }
    @IBInspectable var rightLine: Bool = false { didSet{ drawLines() } }
    @IBInspectable var bottomLine: Bool = false { didSet{ drawLines() } }
    @IBInspectable var topLine: Bool = false { didSet{ drawLines() } }



    func drawLines() {

        if bottomLine {
            add(CGRectMake(0.0, frame.size.height - linesWidth, frame.size.width, linesWidth))
        }

        if topLine {
            add(CGRectMake(0.0, 0.0, frame.size.width, linesWidth))
        }

        if rightLine {
            add(CGRectMake(frame.size.width - linesWidth, 0.0, linesWidth, frame.size.height))
        }

        if leftLine {
            add(CGRectMake(0.0, 0.0, linesWidth, frame.size.height))
        }

    }

    typealias Line = CGRect
    private func add(line: Line) {
        let border = CALayer()
        border.frame = line
        border.backgroundColor = linesColor.CGColor
        layer.addSublayer(border)
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        drawLines()
    }

}

我希望这会有所帮助......