将图像裁剪为矩形

时间:2018-07-25 08:06:41

标签: android

我正在尝试在矩形内裁剪图像,因为已附加图像我能够拍摄和裁剪照片。但是裁切后的图像不在同一位置。我不想使用裁剪图像库

Camera View

这是拍照

Captured Image

这是裁剪的图像,我正在获取 enter image description here

这是我的布局文件

<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>

这就是我这样做的方式

 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);

2 个答案:

答案 0 :(得分:1)

这是因为位图的大小大于屏幕的大小,因此您必须进行一些转换。也就是说,计算比率(位图大小/屏幕大小),然后计算相应的rect(以像素为单位):

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);

注意:如果位图的长宽比(宽度/高度)与设备相同,则该长宽比为bitmapWidth/screenWidthbitmapHeight/screenHeight,如果不是,则应考虑您的位图的显示方式(例如填充高度还是填充宽度?)。

答案 1 :(得分:0)

尝试

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);