将图像裁剪为矩形

3

我正在尝试在矩形框内裁剪图片,如所附图像。我能够拍摄和裁剪图片。但裁剪后的图片位置不同。我不想使用裁剪图片库。

Camera View

这是拍摄的照片

Captured Image

这是我获得的裁剪图像: 在此输入图片描述 这是我的布局文件。
<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);

嗨,你找到解决问题的方法了吗? - Robert
2个回答

1
这是因为Bitmap的尺寸比屏幕尺寸大,所以需要进行一些转换。也就是说,计算比率(位图大小/屏幕大小),然后计算相应的像素矩形:
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,如果不同,则应考虑如何显示位图(例如填充高度或填充宽度?)。

现在的结果是什么?你能打印出值、位图大小、屏幕大小、相对布局矩形等吗?然后你就可以分析这个过程了。 - Hong Duan
1
@WaqarUlHaq,你找到解决问题的方法了吗?我也遇到了同样的问题,如果你有解决方案,我很感兴趣。谢谢。 - ejay

1
尝试这个。
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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接