旋转位图并保持大小

时间:2012-01-07 04:42:20

标签: android

我正在创建一个瓷砖桌面游戏。 我想用一些预先确定的度数旋转一个位图瓷砖片 当我旋转我的位图时,尺寸会发生变化 例如,如果我想要一个75x75的三角形瓷砖片,在旋转时我从这段代码中得到68x68。我怎样才能保持相同的尺寸,以便所有东西都是电路板的尺寸?

以下是我用来旋转的内容:

public class RotatebitmapActivity extends Activity {
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    LinearLayout linLayout = new LinearLayout(this);

    // load the origial BitMap (500 x 500 px)
    Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(), 
           R.drawable.t123);

    int width = bitmapOrg.getWidth();
    int height = bitmapOrg.getHeight();
    int newWidth = 75;
    int newHeight = 75;

    // calculate the scale - in this case = 0.4f
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;

    // createa matrix for the manipulation
    Matrix matrix = new Matrix();
    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);
    // rotate the Bitmap
    matrix.postRotate(120);

    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, 
                      width, height, matrix, true); 


    // make a Drawable from Bitmap to allow to set the BitMap 
    // to the ImageView, ImageButton or what ever
    BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);

    ImageView imageView = new ImageView(this);

    // set the Drawable on the ImageView
    imageView.setImageDrawable(bmd);

    // center the Image
    imageView.setScaleType(ScaleType.CENTER);

    // add ImageView to the Layout
    linLayout.addView(imageView, 
        new LinearLayout.LayoutParams(
                  LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT
            )
    );

    // set LinearLayout as ContentView
    setContentView(linLayout);
}

1 个答案:

答案 0 :(得分:1)

您的代码中发生的是,创建的位图大小正确。但是,所有位图都会自动缩放以适应当前使用的屏幕密度。

有两种方式(我知道)可以获得您想要的结果。

  1. 您可以在创建位图之后以及将其包装到drawable中之前设置位图的密度。为此,请添加类似于:

    的代码

    resizedBitmap.setDensity(DisplayMetric.DENSITY_HIGH);

    此代码设置位图的设计密度,可以防止Android自动缩放图像。

  2. 第二种解决方案更多的是一种方法论,而不是针对这一特定问题的特定解决方案。我不会详细说明,因为Supporting Multiple Screens | Android Developers

  3. 希望有人能够比我能更好地回答你的问题。