旋转后调整大小或剪切

时间:2011-04-25 15:23:01

标签: android

我有一个10x10的tablelayout,每个单元格都包含一个ImageView。我通过在移动事件中更新每个网格中的图片来模拟在此游戏网格中移动。我还旋转图像以使图像与行进方向对齐。我的问题是,当图像旋转时,它会导致我的单元格行和列展开以适应旋转的图像。

我想要的是将图像裁剪为保持在表格行和列的维度内。如果那是不可能的话,那么我想缩放图像以保持在原始表格单元的维度内。

另一个潜在的问题是图像最初会缩放以适应单元格(这是在表格扩展以填充屏幕时自动完成的)。我不想改变那种行为。我只是想在它们旋转时通过表格单元格的原始边界时修剪图像的角落。

我的轮换代码如下:

Matrix matrix = new Matrix();
matrix.postRotate((float) (360 - sector.getShip().getHeading()));
Bitmap bMap = BitmapFactory.decodeResource(image.getContext().getResources(), getShip().getGridSymbol());
image.setImageBitmap(Bitmap.createBitmap(bMap, 0, 0, bMap.getWidth(), bMap.getHeight(), matrix, true));
image.setImageResource(sector.getShip().gridParams.default);

我的表格配置如下:

<TableLayout android:id="@+id/quadrantGrid" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignWithParentIfMissing="true" android:stretchColumns="*" android:background="#000000">
...
<TableRow>
    <TextView android:text="1" android:background="#404040" android:gravity="center"></TextView>
    <ImageView android:id="@+id/grid00"></ImageView>
    <ImageView android:id="@+id/grid01"></ImageView>
    <ImageView android:id="@+id/grid02"></ImageView>
    <ImageView android:id="@+id/grid03"></ImageView>
    <ImageView android:id="@+id/grid04"></ImageView>
    <ImageView android:id="@+id/grid05"></ImageView>
    <ImageView android:id="@+id/grid06"></ImageView>
    <ImageView android:id="@+id/grid07"></ImageView>
    <ImageView android:id="@+id/grid08"></ImageView>
    <ImageView android:id="@+id/grid09"></ImageView>
</TableRow>
...

更新 我找到了解决方案,但我不确定它是最有效的解决方案。

我的所有照片都是25x25。因此操作系统会计算如何缩放这些图像以适应细胞。该解决方案只执行两个操作。首先它旋转,然后它从旋转的图像创建一个较小的图像。 (注意:当我创建图像时,我确保图像的重要部分将包含在一个直径为图像宽度的圆圈内,以便进行此类裁剪)。

我的代码如下。我宁愿在一种方法中执行这两种操作,但我不确定如何将其分解为两步。

Matrix matrix = new Matrix();
matrix.postRotate((float) (360 - sector.getShip().getHeading()));
Bitmap bMap = BitmapFactory.decodeResource(image.getContext().getResources(), getShip().getGridSymbol());
bMap = Bitmap.createBitmap(bMap, 0, 0, 25, 25, matrix, true);
int x = (bMap.getWidth() - 25) / 2;
int y = (bMap.getHeight() - 25) / 2;
image.setImageBitmap(Bitmap.createBitmap(bMap, x, y, 25, 25));

2 个答案:

答案 0 :(得分:1)

尝试添加

android:scaleType="centerCrop" 

到xml布局中的每个ImageView项目。

答案 1 :(得分:1)

最终解决方案必须利用图像的“getMeasuredHeight()”。我没有必要使用getMeasuredWidth(),因为对于我的特定布局,高度是限制因素。

这是最终的位图代码:

private Bitmap getRotatedShipBitmap(SectorGridImageView image,
        Bitmap bitmap, Matrix matrix) {
    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
            bitmap.getHeight(), matrix, true);
    int yHeight = (image.getMeasuredHeight() == 0) ? bitmap.getHeight()
            : image.getMeasuredHeight();
    int xWidth = yHeight;
    int x = (bitmap.getWidth() - xWidth) / 2;
    int y = (bitmap.getHeight() - yHeight) / 2;
    return Bitmap.createBitmap(bitmap, x, y, xWidth, yHeight);
}