Reputation: 6422
I am trying to crop the image within the rectangle as image attachedI'm able to take and crop the picture. But the cropped image is not of same position. I don't want to use crop images library
This is picture taken
This is cropped image, which i'm getting
This is my layout file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.android.camera2basic.AutoFitTextureView
android:id="@+id/texture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
<RelativeLayout
android:id="@+id/rectangle"
android:layout_width="300dp"
android:layout_height="200dp"
android:background="@drawable/rectangle"
android:layout_centerInParent="true"></RelativeLayout>
<FrameLayout
android:id="@+id/control"
android:layout_width="match_parent"
android:layout_height="112dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true">
<Button
android:id="@+id/picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/picture" />
</FrameLayout>
This is how i'm doing this
Rect rectf = new Rect();
//For coordinates location relative to the screen/display
relativeLayout.getGlobalVisibleRect(rectf);
Bitmap croppedBitmap = Bitmap.createBitmap(origBitmap, rectf.left, rectf.top, rectf.width(), rectf.height(), null, false);
Upvotes: 3
Views: 4396
Reputation: 324
try this
int x1 = Image.getWidth() * x_cordinateOfRextangle / screenWidth;
int y1 = Image.getHeight() * y_cordinateOfRextangle / screenHeight;
int width1 = Image.getWidth() * widthOfRectangle / screenWidth;
int height1 = Image.getHeight() * heightOfRectangle / screenHeight;
Bitmap croppedImage = Bitmap.createBitmap(Image, x1, y1, width1, height1);
Upvotes: 1
Reputation: 4294
This is because the Bitmap's size is larger than the screen size, so you have to do some conversions. That is, compute the ratio (bitmap size/screen size), and then calculate the corresponding rect in pixels:
float ratio = bitmap size/screen size; // pseudo code
Bitmap croppedBitmap = Bitmap.createBitmap(origBitmap, rectf.left * ratio,
rectf.top * ratio, rectf.width() * ratio, rectf.height() * ratio, null, false);
Note: if the aspect ratio(width/height) of the bitmap is the same as the device, then the ratio is either bitmapWidth/screenWidth
or bitmapHeight/screenHeight
, if not, then you should consider about your way to display the bitmap(e.g. fill height or fill width?).
Upvotes: 1